how to work with variables with different names in a loop?

조회 수: 43 (최근 30일)
Lucrezia Cester
Lucrezia Cester 2021년 2월 13일
댓글: VBBV 2023년 3월 19일
Hello,
I have a bunch of data taken in the lab which has names such as A1,A2... AN ... ETC.
How can I work with these data sets in a loop such as
for a=1:N
B=A{N} *2
end
where N changes at each iteration and inserts the next data set saved with a different name.
Thanks, Cheers.

채택된 답변

Ameer Hamza
Ameer Hamza 2021년 2월 13일
It is never a good idea to create a variable name like this: A1, A2, ..., AN. Read here: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. There is no good way to access values of these variables in a loop. It is better to create an array which is easier to loop over. For example, create a cell array
A = {A1, A2, A3, .., AN};
for i = 1:numel(A)
B = A{i}*2
end
  댓글 수: 2
Lucrezia Cester
Lucrezia Cester 2021년 2월 13일
Hello, thank you very much for your answer. Can I also ask you, after performing this operation, it only saves the last output.
i=9
for i = 1:numel(A)
B = mat2cell( A{i},[1],[3666 3666 3666 3666 3666 3666])
end
like so
B= 1x6 cell
which is the last iteration where i=9.
instead of
B= (1x9 cell) and inside the cell each of the 9 elements is 1x6
VBBV
VBBV 2023년 3월 19일
A = {A1, A2, A3, .., AN};
for i = 1:numel(A)
B{i} = A{i}*2;
end
B
Use the for loop index i.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by