How to store outputs from a for loop iterations (without overwriting) in a table
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I have a table and I have created a for loop to go over each row and select only the ones I want based on an if condition. My code looks like this:
for k=2
if bla bla bla
storedRow = mytablename(k,:)
end
end
At the moment it stores the row I need but then the next output (row) overwrites my previous one. After my online search for an answer on how to avoid overwriting the outputs from my iterations, I tried to do storedRows(k) = mytable(k,:) but it does not work. I get this error: "You cannot subscript a table using linear indexing (one subscript) or multidimensional indexing (three or more subscripts). Use a row subscript and a variable subscript"
Is the solution different when working with tables? My goal is to have an output table (to keep the same format) only with the selected rows. Thank you so much, in advance, for your help!
2 Kommentare
Joshua
am 27 Mär. 2017
My Matlab is too old to have the table function to check, but your issue might be that you need to do this instead:
for k=2
if bla bla bla
storedRow(k,:) = mytablename(k,:)
end
end
Otherwise it may try to store an entire vector into a 1x1 element in the matrix storedRow. Worth a shot.
Antworten (1)
Sonam Gupta
am 28 Mär. 2017
Since you want to select rows satisfying specific condition and copy those rows in a new table, you can try the code below. It takes advantage of logical indexing in MATLAB.
%creating a table
user = ['A';'B';'A';'C';'B'];
Age = [38;43;38;40;49];
Height = [71;69;64;67;64];
Weight = [176;163;131;133;119];
BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
T = table(user,Age,Height,Weight,BloodPressure);
%creating a new table having only those rows where user is A
new_table = T(T.user=='A',:);
Hope this helps.
Siehe auch
Kategorien
Mehr zu Logical 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!