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

31 vues (au cours des 30 derniers jours)
Leon
Leon le 18 Avr 2024
Modifié(e) : Leon le 21 Avr 2024
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 commentaires
Torsten
Torsten le 18 Avr 2024
"rows2vars" transposes your table, if it is that what you want to achieve.
Leon
Leon le 21 Avr 2024
Modifié(e) : Leon le 21 Avr 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.

Connectez-vous pour commenter.

Réponse acceptée

Steven Lord
Steven Lord le 18 Avr 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 commentaires
Bruno Luong
Bruno Luong le 18 Avr 2024
Modifié(e) : Bruno Luong le 18 Avr 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 le 21 Avr 2024
Modifié(e) : Leon le 21 Avr 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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by