필터 지우기
필터 지우기

Possible to iterate over table rows without a loop index variable?

조회 수: 19 (최근 30일)
Leon
Leon 2024년 4월 18일
편집: Leon 2024년 4월 21일
To iterate over the variables (columns) of a table, you can do this:
my_table = table([1; 2; 3], [4; 5; 6], ["Seven"; "Eight"; "Nine"])
my_table = 3x3 table
Var1 Var2 Var3 ____ ____ _______ 1 4 "Seven" 2 5 "Eight" 3 6 "Nine"
for var = my_table
disp(var)
end
Var1 ____ 1 2 3 Var2 ____ 4 5 6 Var3 _______ "Seven" "Eight" "Nine"
Is there a way to adjust this to operate on each row without using an index variable? Using a loop index variable, as follows, works fine but is a bit less elegant than the column-by-column solution.
for row_index = 1:height(my_table)
row = my_table(row_index, :);
disp(row)
end
Var1 Var2 Var3 ____ ____ _______ 1 4 "Seven" Var1 Var2 Var3 ____ ____ _______ 2 5 "Eight" Var1 Var2 Var3 ____ ____ ______ 3 6 "Nine"
  댓글 수: 2
Torsten
Torsten 2024년 4월 18일
"rows2vars" transposes your table, if it is that what you want to achieve.
Leon
Leon 2024년 4월 21일
편집: Leon 2024년 4월 21일
Thanks. It's useful to know about but I want to get one table row each time, that I can index by the variable name, to be robust to changes in variable order and new variables in the future, whereas with rows2vars I would get a cell array (since the table variables are of different types) and have to index by number. Presumably it's also a bit inefficient converting to cells and using them, though that doesn't matter for my current use case since there is a lot of other processing per loop.

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

채택된 답변

Steven Lord
Steven Lord 2024년 4월 18일
To perform an operation on all rows of a table array you could use rowfun, but that isn't the same as writing a general for loop. I'd personally probably just use the for loop over 1:height(theTableArray).
  댓글 수: 2
Bruno Luong
Bruno Luong 2024년 4월 18일
편집: Bruno Luong 2024년 4월 18일
Some authority suggests using rowfun on table instead of for-loop row indexing if runtime performance matters.
Read the comments following my complain about combinations only providee table as output format.
Transpose the table as Torsen suggets or retreive the content of the table (without the tanle container) are two other work around of performance hi issue.
Leon
Leon 2024년 4월 21일
편집: Leon 2024년 4월 21일
Interesting to know about for if I need more perfomance. I think I will just stick with having an index since I have a lot more processing in each loop, and want to be able to index by name for future-proofing if variables are added or order changed. Thanks

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by