compare matrices with different dimension

조회 수: 1 (최근 30일)
gianluca
gianluca 2015년 1월 10일
댓글: gianluca 2015년 1월 12일
Hi,
A = [100123 1 1 50;
100123 1 2 53;
100123 1 3 55;
100456 2 1 78;
100456 2 2 75;
100789 1 1 80]
B = [100123 1 56;
100456 2 76]
Comparing the 1st and 2nd columns of A and B, I've to compute the difference between each value in the 4th comlumn of A and the values in the 3th column of B.
In the case to compute (A - B), the expected result is a Matrix as
C = [100123 1 1 -6;
100123 1 2 -3;
100123 1 3 -1;
100456 2 1 2;
100456 2 2 -1]
Tnx for any suggestion

채택된 답변

Stephen23
Stephen23 2015년 1월 10일
편집: Stephen23 2015년 1월 11일
You could try this:
>> X = bsxfun(@eq,A(:,1).',B(:,1));
>> Y = bsxfun(@minus,A(:,4).',B(:,3));
>> Z = [A(any(X,1),1:3),Y(X)]
Z =
100123 1 1 -6
100123 1 2 -3
100123 1 3 -1
100456 2 1 2
100456 2 2 -1
It returns only the rows of A for which the first element matches any first row element in B, and in the last column gives the difference of corresponding end elements of A and B.
  댓글 수: 1
gianluca
gianluca 2015년 1월 12일
Thanks Stephen,
your code worked well. As my original data are a little different than the example I've posted, I've added to your code a further logical operation to select the data that have the same key (1st col) and the same number (2nd col). Finally the following code works well for my purpose:
X1 = bsxfun(@eq,A(:,1).',B(:,1));
X2 = bsxfun(@eq,A(:,2).',B(:,2));
X = X1.*X2;
X = logical(X);
Y = bsxfun(@minus,A(:,4).',B(:,3));
Z = [A(any(X,1),1:3),Y(X)];
Your advices have been very useful!

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

추가 답변 (1개)

Image Analyst
Image Analyst 2015년 1월 10일
Try this:
A = [100123 1 1 50;
100123 1 2 53;
100123 1 3 55;
100456 2 1 78;
100456 2 2 75;
100789 1 1 80]
B = [100123 1 56;
100456 2 76]
[rowsA, colA] = size(A);
[rowsB, colB] = size(B);
B_rep = [repmat(B(1,:), [rowsA/rowsB, 1]); repmat(B(2,:), [rowsA/rowsB, 1])]
C = A; % Initialize
C(:, 4) = A(:, 4) - B_rep(:, 3)
However I get:
C =
100123 1 1 -6
100123 1 2 -3
100123 1 3 -1
100456 2 1 2
100456 2 2 -1
100789 1 1 4
Since you, for some reason , want the last row cropped off of C, you can then do this:
C = C(1:end-1,:)
to get exactly what you listed.

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by