Question

I am trying to create a large number of symbolic variables using a for loop, so that I do not have to type each individual variable. Here is my attempt:

for i 1:19
    yi = sym('yi');
end

However, I am getting this error: Unexpected MATLAB expression.

Était-ce utile?

La solution

I don't have access to the Symbolic Math Toolbox but see if this helps:

for i=1:19
 eval(sprintf('y%d = sym(''y%d'')', i,i))
end 

Although, I highly recommend against doing it this way.

Autres conseils

You can use syms and a cell array to generate a comma-separated list to do this:

varname = 'y';
idx = 19;
y = arrayfun(@(x)char(x),sym(varname,[1 idx]),'UniformOutput',false);
syms(y{:})

which creates nineteen distinct symbolic variables. No need for the explicit use of eval. If you want arbitrary numbering this is more flexible and probably faster:

varname = 'y';
idx = [1:3 9:12 17:19];
y = arrayfun(@(x)sprintf([varname '%d'],x),idx,'UniformOutput',false);
syms(y{:})

There are other ways to create the cell array of strings, e.g., using only sprintf and textscan, but that is left as an exercise to the reader.

Here's another (simpler, but less elegant) option that uses the symfun creation capability of syms:

varname = 'y';
idx = 1:19;
y = sprintf([varname '%d,'],idx);
syms(['tmp(' y(1:end-1) ')']);

The symbolic function tmp can safely be cleared afterwards without bothering the other symbolic variables.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top