Move a portion of one table into another, smaller, table.

조회 수: 3 (최근 30일)
Steve K
Steve K 2022년 10월 14일
댓글: Steve K 2022년 10월 17일
I have two large csv files which I have imported using readtable. The contain related data but one has many more rows than the other. I have a common column between the two. I want to pull variables from the larger one at instances where the common column matches between the two tables. Forgive my syntax a bit here since I do not have matlab on the computer I am writing the question from.
table_A.VariableNames={'x' 'y' 'z'}
table_A=[.98 .3 .9;
.94 .1 .3;
.67 .1 .3;
.56 .7 .4;
.72 .4 .3;
.64 .6 .2]
table_B.VariableNames={'x' 'q' 'e'}
table_B=[.98 -.201 -.239;
.72 -2.18 -0.05;
.67 -.228 -1.28]
So in the given example I want to take the values of y and z, in table A, where x values match those in table B, and append them onto table B. I attempted to create a logical index vector with;
X_needed=table_A.x==table_B.x
I would then use that index vector to create a table with the desired values of y and z to append onto table B.
However, when I try this I get the error that "matrix dimensions must agree". I think I can reach the solution with a loop, but there must be a better way to solve this.
Thanks for any help provided.

채택된 답변

Voss
Voss 2022년 10월 14일
table_A = array2table([ ...
.98 .3 .9;
.94 .1 .3;
.67 .1 .3;
.56 .7 .4;
.72 .4 .3;
.64 .6 .2], ...
'VariableNames',{'x' 'y' 'z'})
table_A = 6×3 table
x y z ____ ___ ___ 0.98 0.3 0.9 0.94 0.1 0.3 0.67 0.1 0.3 0.56 0.7 0.4 0.72 0.4 0.3 0.64 0.6 0.2
table_B = array2table([ ...
.98 -.201 -.239;
.72 -2.18 -0.05;
.67 -.228 -1.28], ...
'VariableNames',{'x' 'q' 'e'})
table_B = 3×3 table
x q e ____ ______ ______ 0.98 -0.201 -0.239 0.72 -2.18 -0.05 0.67 -0.228 -1.28
[~,idx] = ismember(table_B.x,table_A.x);
table_B{:,{'y' 'z'}} = table_A{idx,{'y' 'z'}};
disp(table_B);
x q e y z ____ ______ ______ ___ ___ 0.98 -0.201 -0.239 0.3 0.9 0.72 -2.18 -0.05 0.4 0.3 0.67 -0.228 -1.28 0.1 0.3
  댓글 수: 2
Steve K
Steve K 2022년 10월 14일
I'll try this out thanks.
Steve K
Steve K 2022년 10월 17일
So this definitely would have worked. Except I learned that my data doesn't have the matching column that I thought it did.

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

추가 답변 (0개)

카테고리

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

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by