Matlab for loop with string letters
15 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Davindra Usov
am 28 Mär. 2023
Kommentiert: Stephen23
am 29 Mär. 2023
Hi everyone,
I have a table (T) that contains data and have extracted column data from it as follows:
data_1_forward = T.foward_wheels + 435;
data_1_backwards = T.backwards_wheels + 435;
data_1_left = T.left_wheels + 435;
I want to put this in a loop since it is repeated code but unsure on how to do this with strings in the index. I also want the loop to output data_1_foward, data_1_backwards... as separate arrays or vectors.
Many thanks
1 Kommentar
Stephen23
am 29 Mär. 2023
"I also want the loop to output data_1_foward, data_1_backwards... as separate arrays or vectors."
Akzeptierte Antwort
Walter Roberson
am 28 Mär. 2023
numvars = width(T);
data_1 = cell(numvars,1);
for K = 1 : numvars
data_1{K} = T{:,K};
end
Now, data_1 is a cell array with one entry for each variable.
I also want the loop to output data_1_foward, data_1_backwards... as separate arrays or vectors.
We firmly recommend against creating variable names on the fly. http://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
You might want to consider
numvars = width(T);
vars = T.Properties.VariableNames;
data_1 = struct();
for K = 1 : numvars
thisvar = vars{K};
data_1.(thisvar) = T.(thisvar);
end
This would create a struct named data_1 that has one field for each variable in the table.
See also table2struct
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Cell Arrays 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!