Question

I need to create a symbolic matrix in MATLAB. It can be done statically as

syms a11 a12 a21 a22;
A = [a11 a12; a21 a22];

or using compact syntax as

A = sym('A%d', [2 2]);

However i don't see how any of these syntax's should allow dynamic initialization. I would like to initialize each matrix element individually using two loops. One shot at a possible syntax (it's NOT valid MATLAB syntax) could be

syms a x1;
P = sym(zeros(n,n));
for l = 1:n
   for m = 1:n
      kl = l; km = m;
      P(l,m)(x1) = a*sin(kl*x1)*sin(km*x1);
   end
end

where I used the (invalid) syntax P(l,m)(x1) to specify that each element in P is a function of x1. Hence P(2) would be an (n,n) matrix with elements P(l,m) = a*sin(kl*2)*sin(km*2). I know it's possible to construct the P by building the matrix string (A=[...]) on run time and evaluating using eval. Something like

syms a x1;
command = [];
for i = 1:n
    for j = 1:n
        kl = i; km = j;
        command = [command ' + a*sin(' num2str(kl) '*x1)*sin(' num2str(km) '*x1)'];
        if(j < n) command = [command ',']; end
    end
    if(i < n) command = [command ';']; end
end
eval(['P(x1) = [' command '];'])

However, using eval is bad practice, so I see this solution only as a last resort. Is there any correct way to achieve my goal?

NB: I have written the elements P(l,m) = a*sin(kl*x1)*sin(km*x1) to simplify the code. The actual expression is P(l,m) = sin(kl*x1)*sin(km*x1)*epsilon + kl*km*cos(kl*x1)*cos(km*x1).*b + km*cos(km*x1)*sin(kl*x1)-kl*cos(kl*x1)*sin(km*x1)/(kl^2-km^2).

Was it helpful?

Solution

If you're just trying to avoid the for loops, you can use meshgrid, which hides them from you:

syms a x1
n = 3;
x = meshgrid(1:n)*x1; % multiplying by the symbolic x1 makes x symbolic
P = a*sin(x).*sin(x.');

which returns

P =

[         a*sin(x1)^2,   a*sin(2*x1)*sin(x1),   a*sin(3*x1)*sin(x1)]
[ a*sin(2*x1)*sin(x1),         a*sin(2*x1)^2, a*sin(2*x1)*sin(3*x1)]
[ a*sin(3*x1)*sin(x1), a*sin(2*x1)*sin(3*x1),         a*sin(3*x1)^2]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top