How to store outputs from a for loop iterations (without overwriting) in a table

3 Ansichten (letzte 30 Tage)
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
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.
Paula Banca
Paula Banca am 29 Mär. 2017
I tried your suggestion:
storedRow(k,:) = mytablename(k,:)
but it doesn't work unfortunately. It produces the same 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"

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Sonam Gupta
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.
  1 Kommentar
Paula Banca
Paula Banca am 29 Mär. 2017
Thank you! That makes sense and it avoids the loop. However, I have many specific conditions I need to meet (6 conditions) to select my rows. In your example, how could you select both user == 'A' and height higher than 65? I tried to use && but Matlab says "Conversion to logical from timetable is not possible". Many thanks for your help!

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by