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

9 ビュー (過去 30 日間)
Paula Banca
Paula Banca 2017 年 3 月 23 日
コメント済み: Paula Banca 2017 年 3 月 29 日
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 件のコメント
Joshua
Joshua 2017 年 3 月 27 日
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 2017 年 3 月 29 日
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"

サインインしてコメントする。

回答 (1 件)

Sonam Gupta
Sonam Gupta 2017 年 3 月 28 日
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 件のコメント
Paula Banca
Paula Banca 2017 年 3 月 29 日
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!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by