How to assign a unique variable to each output in a for loop?
조회 수: 7 (최근 30일)
이전 댓글 표시
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
채택된 답변
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
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
2017년 6월 7일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!