save for loop variable in workspace

Hello.
I am new to coding and have a question.
I'm running a script which gives produces many variables in the output inclduing a 1x1 structure with 6 fields, I want to save one of the fields: "PM.res" each time. I'm using loop numbers:
loop = 1
at the beginning and
loop = loop + 1
in the for loop so I will incorporate this when saving but I want to know how. I want to save each one as a variable in the workspace, so it can be used within the rest of the for loop.
Thank you.

回答 (1 件)

Stephen23
Stephen23 2021 年 7 月 1 日
編集済み: Stephen23 2021 年 7 月 1 日

0 投票

Given that you are apparently incrementing your own loop counter then presumably you have a WHILE loop.
In that case, try this:
C = {};
loop = 1;
while ..
.. your code here
C{end+1} = PM.res;
loop = loop+1;
end
If the total number of iterations is known in advance then a FOR loop would be simpler and more efficient.

2 件のコメント

Sarah Philips
Sarah Philips 2021 年 7 月 1 日
編集済み: Sarah Philips 2021 年 7 月 1 日
Thank you for your help. If it is simipler, I do know that there will be 720 iterations what would you suggest?
I haven't used a while loop, but I included the counter to keep track of which part of the data the for loop is at.
Stephen23
Stephen23 2021 年 7 月 2 日
"...but I included the counter to keep track of which part of the data the for loop is at."
FOR loops already have a "counter", in most cases there is no need to duplicate that information with your own separately-defined "counter" as well. Therefore you can write simpler and more efficient code:
N = 720;
C = cell(1,N);
for k = 1:N
..
C{k} = PM.res;
end

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2021 年 7 月 1 日

コメント済み:

2021 年 7 月 2 日

Community Treasure Hunt

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

Start Hunting!

Translated by