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

5 ビュー (過去 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.
  1 件のコメント
ampaul
ampaul 2017 年 6 月 7 日
Thank you. You are right to suggest the use of arrays.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by