I would like to achieve something like this:
for(i=1:n)
x[i]=value %create a new variable for each x: x1,x2,x3
end
any recommendations?
Thank you
You do not need different variables. You can do it with eval
but I would not go into it and recommend it.
My answer depends on the dimensions of your value
variable. I would say if it is a single number then use the following:
for i=1:n
x(i)=value;
end
If value
is a string or matrix or different size vectors etc., then use cell array.
for i=1:n
x{i}=value; %notice curly braces.
end
You should never do this. Just to be clear, don't use eval to do this this way:
eval(['x' num2str(count) ' = i^2']);
Another alternative is to make each x[i]
a field in a structure S
. Then you can do something like this
S = struct;
i = 1:n;
tmp = strsplit(num2str(i));
for i = i
S.(['x',tmp{i}]) = value(i);
end
Then calling S
yields
S =
x1: 0.6557
x2: 0.0357
x3: 0.8491
x4: 0.9340
...
(In this case I just used random numbers for value
.) You cannot make x.1, x.2
and so on because fields that start with a numerical character like '1'
are not allowed. If you were content with fields like a, b, c ...
then you could generate xa, xb, xc ...
in a similar way to above.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.