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

19 次查看(过去 30 天)
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