필터 지우기
필터 지우기

How do I loop trough variables

조회 수: 2 (최근 30일)
René Moerman
René Moerman 2020년 3월 6일
댓글: Guillaume 2020년 3월 6일
How do I loop throug variables like this?
a=1;
b=2;
c=3;
for Q=[a b c]
Y=Q
end
The result i would like is:
y = 1
y = 2
y = 3
  댓글 수: 5
Guillaume
Guillaume 2020년 3월 6일
편집: Guillaume 2020년 3월 6일
Are the variables actually tables which would show in the variable browser as a 9x14 table, or cell arrays which would show in the variable browser as 9x14 cell?
Also, what do you want to do with your loop?
René Moerman
René Moerman 2020년 3월 6일
They are cell arrays,
S1R1, S1R2, S1R3 ...... are my measurement positions from my experiment. They are cell arrays with in every collumn a different parameter.
I want to loop these variables so I can go through all my measurement positions and then extract the parameters i want from these positions so I can plot them.
like this:
for Q = [S1R1 S1R2 S1R3 ect. ect.]
F = Q(2:end,1);
F = cell2mat(F);
T30 = Q(2:end,2);
T30 = cell2mat(T30);
rT30 = Q(2:end,3);
rT30 = cell2mat(rT30);
T20 = Q(2:end,4);
T20 = cell2mat(T20);
semilogx(F,T30)
hold on
end

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

답변 (1개)

Stephen23
Stephen23 2020년 3월 6일
편집: Stephen23 2020년 3월 6일
"Why is that?"
Your confusion stems from several things.
  1. [] square brackets are a concatenation operator, not a "list" operator (which MATLAB does not have). So you took three 9x14 cell arrays and concatenated them horizontally to get one 9x42 cell array (not a "list" of separate arrays as you seemed to be expecting). If you want to store several arrays in a container, then use a cell array.
  2. Without realizing it, you are looping over the columns of that 9x42 cell array. The for documentation explains that if the values to be iterated over are a non-vector array, then for will iterate over its columns. I have never seen anyone rely on this "feature".
I would avoid your approach of iterating over data or over arrays: it is much more robust to iterate over indices:
C = {arr1,arr2,arr3}; % cell array
for k = 1:numel(C)
Y = C{k};
... do whatever with Y
end
  댓글 수: 2
Guillaume
Guillaume 2020년 3월 6일
"I have never seen anyone rely on this "feature"."
I use it sometimes, but it is indeed very rare that you just want to iterate over columns without knowing their indices.
Guillaume
Guillaume 2020년 3월 6일
"would avoid your approach of iterating over data or over arrays"
Totally agree.
Even better would be to avoid creating these numbered arrays in the first place. There should only be one variable to start with, either a cell array or in this case since all the arrays are the same size, a 3D matrix.

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

카테고리

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