How to assign a unique variable to each output in a for loop?
7 views (last 30 days)
Show older comments
mu=3; %mean value
s=0.5; %stepsize
P=1:s:20; %time period
g=2; %magnitude of gradient trend
sigma = 5; %noise level
for iterations = 1:10
r=rand(1,length(P)); %generates a vector of random numbers equal to the time period length
inc1= mu + sigma*r + g*P
end
This is my current code. I'm happy with it, except for one problem. Currently, the loop runs 10 times, but once everything is complete, I am left with two outputs, inc1 and r. I would like for my code to store each output as a new variable (where the first run stores the data as inc1 and r1, the second run stores the data as inc2 and r2, and so on until inc10 and r10. I cannot locate the solution to this. Any ideas?
0 Comments
Accepted Answer
Rik
on 7 Jun 2017
Some people have very strong opinions on this topic. You should NOT dynamically create variable names. It makes for unreadable, slow code that is impossible to debug. I even hesitate to tell you that eval is the function you were looking for. Don't use it.
You should use something like a cell array in this case. Instead of the result being inc1, inc2 and inc3, the result will be inc{1}, inc{2} and inc{3}.
2 Comments
Image Analyst
on 8 Jun 2017
I wouldn't even mess with cell arrays. They can be tricky and complicated so don't use them if you don't need to. I'd just use a regular, simpler 2-D numerical array:
mu = 3; % mean value
s = 0.5; % stepsize
P = 1:s:20; % time period
g = 2; % magnitude of gradient trend
sigma = 5; % noise level
incl = zeros(10, length(P));
for iterations = 1:10
r = rand(1, length(P)); % Generates a vector of random numbers equal to the time period length
inc1(iterations, :) = mu + sigma*r + g*P;
end
If you still want to dare to use cell arrays, please read the FAQ on them to get a better intuitive feeling for when you're supposed to use brackets [], parentheses (), or braces {}:
More Answers (1)
Image Analyst
on 7 Jun 2017
See the FAQ for why you should not try this horrible idea: http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F
Let's say you made an inc10. Presumably you're going to try to use in somewhere in your code and so you'd do something like
newVariable = 2 * inc10;
But what if you ran the code and it only went up to inc8? What would you do with the line of code where you're trying to use inc10? It would throw an error. It's much better to use arrays.
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!