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

29 views (last 30 days)
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 Comments
Torsten
Torsten on 18 Apr 2024
"rows2vars" transposes your table, if it is that what you want to achieve.
Leon
Leon on 21 Apr 2024
Edited: Leon on 21 Apr 2024
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.

Sign in to comment.

Accepted Answer

Steven Lord
Steven Lord on 18 Apr 2024
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 Comments
Bruno Luong
Bruno Luong on 18 Apr 2024
Edited: Bruno Luong on 18 Apr 2024
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 on 21 Apr 2024
Edited: Leon on 21 Apr 2024
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

Sign in to comment.

More Answers (0)

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!