Borrar filtros
Borrar filtros

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

1 visualización (últimos 30 días)
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 comentarios
Joshua
Joshua el 27 de Mzo. de 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 el 29 de Mzo. de 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"

Iniciar sesión para comentar.

Respuestas (1)

Sonam Gupta
Sonam Gupta el 28 de Mzo. de 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 comentario
Paula Banca
Paula Banca el 29 de Mzo. de 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!

Iniciar sesión para comentar.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by