Keep specific column variables and delete others?

71 ビュー (過去 30 日間)
Tyla Ono
Tyla Ono 2018 年 8 月 18 日
コメント済み: Walter Roberson 2023 年 4 月 1 日
Hi, I have a table with a list of column variables (Eg: [[Var1 Var2 Var3 Var4 VarN]. I am trying to keep only specific variables and associated column data, whilst deleting all others.
For example, I want only variable 2 and 4, while deleting all other columns. Desired output --> [Var2 Var4]
It is possible to output only the desired columns without individually deleting unwanted variables?

採用された回答

Paolo
Paolo 2018 年 8 月 18 日
Var1 = {'Sanchez';'Johnson';'Li';'Diaz';'Brown'};
Var2 = [38;43;38;40;49];
Var3 = logical([1;0;1;0;1]);
T = table(Var1,Var2,Var3)
To keep columns one and three:
T = [T(:,1) T(:,3)]
T =
5×2 table
Var1 Var3
_________ _____
'Sanchez' true
'Johnson' false
'Li' true
'Diaz' false
'Brown' true
Adapt the code for columns 2 and 4.

その他の回答 (1 件)

Alex Whiteway
Alex Whiteway 2022 年 5 月 19 日
I know this is a bit old, but I wanted to put my preferred method using column names:
Var1 = {'Sanchez';'Johnson';'Li';'Diaz';'Brown'};
Var2 = [38;43;38;40;49];
Var3 = logical([1;0;1;0;1]);
T = table(Var1,Var2,Var3)
%Keep just Var1 and Var3
Tnew = T(:,{'Var1', 'Var3'});
  2 件のコメント
Walter Roberson
Walter Roberson 2023 年 4 月 1 日
Nariman Mahmoudi comments to @Alex Whiteway
"much more efficient"
Walter Roberson
Walter Roberson 2023 年 4 月 1 日
Testing efficiency:
Var1 = {'Sanchez';'Johnson';'Li';'Diaz';'Brown'};
Var2 = [38;43;38;40;49];
Var3 = logical([1;0;1;0;1]);
T = table(Var1,Var2,Var3)
T = 5×3 table
Var1 Var2 Var3 ___________ ____ _____ {'Sanchez'} 38 true {'Johnson'} 43 false {'Li' } 38 true {'Diaz' } 40 false {'Brown' } 49 true
%Keep just Var1 and Var3
tic; Tnew1 = T(:,{'Var1', 'Var3'}); toc
Elapsed time is 0.009980 seconds.
tic; Tnew2 = T(:,[1 3]); toc
Elapsed time is 0.006850 seconds.
tic; Tnew3 = [T(:,1), T(:,3)]; toc
Elapsed time is 0.037788 seconds.
So the {'Var1', 'Var3'} version is considerably more efficient than the [T(:,1), T(:,3)] option -- but it is not as efficient as indexing by variable numbers.

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

カテゴリ

Help Center および File ExchangePerformance and Memory についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by