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

조회 수: 9 (최근 30일)
ampaul
ampaul 2017년 6월 7일
댓글: Image Analyst 2017년 6월 8일
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?

채택된 답변

Rik
Rik 2017년 6월 7일
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
ampaul
ampaul 2017년 6월 7일
Thank you. This is much more organized.
Image Analyst
Image Analyst 2017년 6월 8일
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 {}:

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2017년 6월 7일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by