Question

From a computation in Mathematica I got a huge matrix with numbered variables of the form a[1],...,a[100] in some of the entries. I would like to import this matrix as a template to matlab and then substitute random numbers (normally distributed) in place of the variables. I am completely unfamiliar with the support of symbolic variables in Matlab and am not sure whether it supports indexed symbolic variables. I would need some function that searches for the a[k] and replaces them with a random number.

In Mathematica I have matrices square matrices of length 2^n where which get more and more sparse as n grows and depend on 5*n (yet symbolic) variables a[k]. For n=2 the matrix is not yet sparse at all and looks like (in Mathematica-Code):

{{a[3] + a[3], a[7] - I a[8], a[10], I a[8]},

{I a[8], +a[6], I a[5], -I a[9] - a[8]},

{a[7] + I a[8], +a[2], I a[5], -a[7]},

{I a[8], a[2], a[2] + I a[15], -a[8]}}

There exists a script ToMatlabwhich converts the Mathematica notation for matrices to the Matlab notation. I have basically all freedom in renaming the variables as it is most suitable for use in Matlab. Now I would like to create a function in Matlab which returns this exact matrix (for fixed n would be sufficient for now, so the matrix is really fixed) and replaces the a[k] with a normally distributed random number.

Was it helpful?

Solution

Assuming you have a cell array of strings (much bigger than this simple example):

import = {'a1','a2';'a2','a4'};

Then you can replace 100 values with normally distributed random numbers as follows (obviously you will want to replace constants etc with the values you need):

newMatrix = zeros(size(import));

% generate 100 random numbers:
mean = 123.45;
stdDev = 21.0;
N = 100;
randVals = randn(1,N) * stdDev + mean;

for ii=1:N
  indx = find(ismember(import, sprintf('a%d',ii)));
  newMatrix(indx) = randVals(ii);
end

The new values will be in the matrix newMatrix

This is not super efficient; but it may be a start, and it may get other answers flowing (if you can confirm that this does indeed do what you intend - still not 100% sure I understand your question).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top