How can I compare columns from 2 different numeric arrays and when they match define a new column in array A with the value of a second column in array B?

For example:
A(:,1)= [1 2 3 4 5 6]
B(:,1)=[0 0 0 2 0 5]
B(:,2)=[20 20 20 10 80 60]
And the goal is to create the following (zeros indicating there was no match):
A(:,2)=[0 10 0 0 60 0]

 Accepted Answer

A(:,1)=[1 2 3 4 5 6]
B(:,1)=[0 0 0 2 0 5]
B(:,2)=[20 20 20 10 80 60]
%-----------------------------
idx=B(:,1)~=0
A(B(idx,1),2)=B(idx,2)

3 Comments

Thanks Azzi, that worked perfectly. But as I got deeper in my task I realized that matching the arrays on a single column of each was insufficient as in several cases the values in the arrays repeat (within a column). Essentially there are different conditions, coded in another column. So the matching would also need to take that into consideration. I've played around with trying to expand your solution to multiple column comparison but haven't had any luck.
Describing the problem in another way: When Array_A column1 = x and column2 = y, find the row in Array_B were the same is true and extract the value of Array_B column3 (into column3 in Array_A).
Here's an extended example where two matches would be found:
A(:,1)=[1 1 2 2]
A(:,2)=[1 2 3 4]
B(:,1)=[1 1 2 2]
B(:,2)=[4 1 3 5]
B(:,3)=[10 20 30 40]
And the desired result would be:
A(:,3)=[20 0 30 0]
Much obliged for your help,
Maybe you want this
A(:,1)=[1 1 2 2];
A(:,2)=[1 2 3 4]
B(:,1)=[1 1 2 2];
B(:,2)=[4 1 3 5];
B(:,3)=[10 20 30 40]
n=size(A,2);
[ii,jj]=ismember(A,B(:,1:n),'rows')
A(ii,3)=B(nonzeros(jj),n+1)
Yep, that does the trick! Your abilities, and those of others on this site, blow my mind. I long for a break in my work long enough to learn more.
Thanks again,

Sign in to comment.

More Answers (0)

Categories

Find more on Software Development in Help Center and File Exchange

Asked:

on 25 Apr 2014

Commented:

on 27 Apr 2014

Community Treasure Hunt

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

Start Hunting!