How to assign a unique variable to each output in a for loop?

7 visualizaciones (últimos 30 días)
ampaul
ampaul el 7 de Jun. de 2017
Comentada: Image Analyst el 8 de Jun. de 2017
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?

Respuesta aceptada

Rik
Rik el 7 de Jun. de 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 comentarios
ampaul
ampaul el 7 de Jun. de 2017
Thank you. This is much more organized.
Image Analyst
Image Analyst el 8 de Jun. de 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 {}:

Iniciar sesión para comentar.

Más respuestas (1)

Image Analyst
Image Analyst el 7 de Jun. de 2017
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.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by