필터 지우기
필터 지우기

How can use a for loop to name a matrix?

조회 수: 26 (최근 30일)
Matthew
Matthew 2015년 3월 27일
편집: Stephen23 2023년 9월 12일
After each iteration of my for loop, a matrix is produced. I want to name that matrix based on the number of the iteration. This is what I have so far:
for trials = 1:max_trials
a = int2str(trials);
a = output_matrix;
However, Matlab just stores the last matrix produced under the variable 'a'. How can I get it to store each matrix under its respective iteration? For example, if max_trials = 3, how would I get three separate matrices labelled '1', '2' and '3'?
Thank you!
  댓글 수: 1
Asghar Molaei
Asghar Molaei 2021년 5월 15일
Thank you very much for asking this question. It was my question too.

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

채택된 답변

Stephen23
Stephen23 2015년 3월 27일
편집: Stephen23 2023년 9월 12일
Use a cell array like this:
out = cell(1,max_trials);
for trial = 1:max_trials
out{trial} = ... your calculation here
end
Avoid creating dynamically named variables:
  댓글 수: 1
Asghar Molaei
Asghar Molaei 2021년 5월 15일
Your tips were very helpful. Thank you

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

추가 답변 (1개)

David Young
David Young 2015년 3월 27일
One way is to use a cell array, like this
for trials = 1:max_trials
< compute result, assign to a >
output_matrix{trials} = a;
end
Then output_matrix{k} is the value of the a matrix for iteration k.
Don't try to assign the result of each iteration to a different variable by constructing different names inside the loop - it's a very bad way to do it.
  댓글 수: 1
David Young
David Young 2015년 3월 27일
... as Stephen Cobeldick explains in more detail in his answer.

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

카테고리

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