Carlos Danger
Carlos Danger

Reputation: 155

MATLAB - Can't create symbolic variables through array loop

I have this cell array

MatrixF = 

{3x1 cell}    {3x1 cell}

MatrixF{1}

ans = 

'f1'
'f2 '
'f3 '

MatrixF{2}

ans = 

'x1'
'x2 '
'x3 '

And I want to convert each item in the MatrixF array into a symbolic variable. I thought that this loop would do that

 [a, b] = size(MatrixF);
 for i=1:b;
     [c,d] = size(MatrixF{i});
     for j=1:c;
        sym(MatrixF{i}{j});
     end;
 end;

But instead, the only output that I get is the variable ans, which is a 1x1 array. Why is ans being declared as a sym instead of the individual variables thelselves, which are being called and accessed?

Upvotes: 0

Views: 188

Answers (1)

TroyHaskin
TroyHaskin

Reputation: 8401

ans is being declared as a sym because the sym function requires an explicit output argument to generate a Symbolic Variable. This behavior is different from the syms function that uses the semantics of command form to poof a variable into existence.

Therefore, you can do the following:

 [a, b] = size(MatrixF);
 for i=1:b
     [c,d] = size(MatrixF{i});
     for j=1:c
        MatrixF{i}{j} = sym(MatrixF{i}{j});
     end
 end

Although, I'd suggest doing the much cleaner (and probably faster):

>> x = sym('x',[3,1])
x =
 x1
 x2
 x3

>> f = sym('f',[3,1])
f =
 f1
 f2
 f3

Upvotes: 2

Related Questions