How to write a for loop that indexes the variable name and the funciton?
46 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Jesse Finnell
am 8 Okt. 2019
Bearbeitet: Fabio Freschi
am 8 Okt. 2019
I want to write a loop that will convert a table to an array for many different tables. Each table is named x1, x2,... and I want to keep those same names, so the x1 table goes through the loop and becomes x1, the array.
I'm not sure how to set up the statement to get this to work.
for k = 1:5
x(k) = table2array(x(k))
end
is a generic version of what I started with, but this is obviously incorrect.
This was previously done manually, which works but is slow and takes up a lot of lines.
x1 = table2array(x1);
x2 = table2array(x2);
x3 = table2array(x3);
This goes on for 20 lines.
0 Kommentare
Akzeptierte Antwort
Fabio Freschi
am 8 Okt. 2019
Bearbeitet: Fabio Freschi
am 8 Okt. 2019
Don't do that! Check this out: https://it.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
You can use cell arrays instead
% store your data in x{k}
for k = 1:5
x{k} = myNiceTable;
end
now you have x{k} instead of xk
% then convert to array
for k = 1:5
x{k} = table2array(x{k});
end
If you really want to use variables with dynamically generated names you should make use of eval
for k = 1:5
sprintf('x%d = table2array(x%d)', k,k);
end
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!