1

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

1
  • MATLAB itself recommends not to create a variable at each iteration, so what should we say? Commented Feb 2, 2014 at 21:23

3 Answers 3

8

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
Sign up to request clarification or add additional context in comments.

2 Comments

the answer with eval is already here. I don't have to show it to you.
+1. @user3228903 And remember to preallocate if possible
3

You should never do this. Just to be clear, don't use eval to do this this way:

eval(['x' num2str(count) ' = i^2']);

Comments

0

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 x.a, x.b, x.c ... in a similar way to above.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.