MATLAB Answers

How to extract row intervals from a table to create a new one.

2 ビュー (過去 30 日間)
Philippe Corner
Philippe Corner 2018 年 1 月 31 日
コメント済み: Peter Perkins 2018 年 2 月 7 日
if I have a table
T:
v1 v2 v3 v4
a 1 1 5
b 3 3 7
c 2 5 7
d 5 5 2
e 5 7 7
How could i obtain all the columns from b and d rows as T2 table?
T2:
v1 v2 v3 v4
b 3 3 7
c 2 5 7
d 5 5 2

  0 件のコメント

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

回答 (2 件)

Walter Roberson
Walter Roberson 2018 年 1 月 31 日
編集済み: Walter Roberson 2018 年 1 月 31 日
T2 = T1(2:4,:);

  4 件のコメント

表示 1 件の古いコメント
Walter Roberson
Walter Roberson 2018 年 1 月 31 日
first_row = find(T1.v1 == b, 1, 'first');
last_row = find(T1.v1 == d, 1, 'first');
if isempty(first_row); error('b not found'); end
if isempty(last_row); error('d not found'); end
if first_row > last_row
row_vec = first_row : -1 : last_row;
else
row_vec = first_row : last_row;
end
T2 = T1(row_vec, :);
I had to make arbitrary decisions about what you wanted done if one of the values was missing, or if the values appear in the other order.
Philippe Corner
Philippe Corner 2018 年 2 月 1 日
Thanks Mr. Walter, it is showing a mistake due to the == when I adapted it to my code.. do you have an idea why could it be?
Walter Roberson
Walter Roberson 2018 年 2 月 1 日
The == could have difficulty depending on the data type involved. Perhaps you need
first_row = find(strcmp(T1.v1, 'b'), 1, 'first');
last_row = find( strcmp(T1.v1, 'd'), 1, 'first');

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


Peter Perkins
Peter Perkins 2018 年 2 月 1 日
Walter interpreted "all the columns from b and d rows" as "FROM b TO d". I'm going to interpret it as "b AND d".
If the first variable in T has unique values, turn it into the row names, and just subscript:
T.Properties.RowNames = T.Var1;
T.Var1 = [];
t({'b' 'd'},:)
If they're not unique, use ismember to create a logical vector to use as a row subscript.

  2 件のコメント

Walter Roberson
Walter Roberson 2018 年 2 月 1 日
No, notice they wanted three lines of results, which can only be explained by wanting a range.
Peter Perkins
Peter Perkins 2018 年 2 月 7 日
right you are.

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by