Select columns of a table using matching column names

조회 수: 153 (최근 30일)
Enrico Gambini
Enrico Gambini 2022년 6월 14일
댓글: Voss 2022년 6월 15일
Hello everyone!
I'm facing the following problem: I have a cell array containing strings, let's call it "v"
On the other hand I have a huge table , let's call it "T", from which I want to select only the columns that have the column name that corresponds to the names contained in vector "v".
Any kind of help will be appreciated
Thank you

채택된 답변

Voss
Voss 2022년 6월 14일
v = {'Var1' 'Var3'}
v = 1×2 cell array
{'Var1'} {'Var3'}
T = table([1;2;3],[4;5;6],[7;8;9])
T = 3×3 table
Var1 Var2 Var3 ____ ____ ____ 1 4 7 2 5 8 3 6 9
% a table of the selected columns of T:
new_T = T(:,v)
new_T = 3×2 table
Var1 Var3 ____ ____ 1 7 2 8 3 9
% or, the data from the selected columns of T:
new_T_data = T{:,v}
new_T_data = 3×2
1 7 2 8 3 9
  댓글 수: 2
Enrico Gambini
Enrico Gambini 2022년 6월 15일
It worked, thank you! And what if not all the elements in v are present as column names in T?
Voss
Voss 2022년 6월 15일
If not all elements of v are column names of T, you can use ismember to get just the elements of v that do correspond to column names of T:
v = {'Var1' 'Var3' 'Var4'}
v = 1×3 cell array
{'Var1'} {'Var3'} {'Var4'}
T = table([1;2;3],[4;5;6],[7;8;9])
T = 3×3 table
Var1 Var2 Var3 ____ ____ ____ 1 4 7 2 5 8 3 6 9
v_to_use = v(ismember(v,T.Properties.VariableNames))
v_to_use = 1×2 cell array
{'Var1'} {'Var3'}
And use that the same as v was used before:
new_T = T(:,v_to_use)
new_T = 3×2 table
Var1 Var3 ____ ____ 1 7 2 8 3 9
new_T_data = T{:,v_to_use}
new_T_data = 3×2
1 7 2 8 3 9

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by