Asked by suchismita
on 5 May 2015

I have a matrix A,

[1 5

2 6

3 6

4 7

5 6]

and I have another matrix B as

[1 2

1 3

1 4

1 5

2 3

2 4

3 4

3 5

4 5]

now i want to compare B with a and i want to replace 2nd column of B with A data for example,

[1 5

1 5

1 5

1 5

2 6

2 6

3 6

3 6

4 7]

in first column when there is 1 it will take the value of matrix A's second column data as 5 and when first column is having 2 it will take the value of 2 from matrix A.

please please help me.

Answer by David Sanchez
on 5 May 2015

Accepted Answer

for k=1:length(B)

x = A(:,1)==B(k,1);

B(k,2) = A(x,2);

end

B =

1 5

1 5

1 5

1 5

2 6

2 6

3 6

3 6

4 7

suchismita
on 5 May 2015

thank u so much....

Stephen Cobeldick
on 5 May 2015

Andrei Bobrov's solution is much neater.

Sign in to comment.

Answer by Andrei Bobrov
on 5 May 2015

Edited by Andrei Bobrov
on 5 May 2015

[lo,ii] = ismember(B(:,1),A(:,1));

out = B;

out(lo,2) = A(ii(lo),2);

Stephen Cobeldick
on 5 May 2015

Very nice solution, although it took me a while to realize that l0 is a variable. it looks similar to the number 10, especially when it is being used as an index.

If the nomenclature is clearer then this solution is much easier to read:

>> [ism,idx] = ismember(B(:,1),A(:,1));

>> out = B;

>> out(ism,2) = A(idx(ism),2)

out =

1 5

1 5

1 5

1 5

2 6

2 6

3 6

3 6

4 7

Andrei Bobrov
on 5 May 2015

Hi Stephen! I corrected..

suchismita
on 5 May 2015

thank u so much.....

Sign in to comment.

Answer by Nobel Mondal
on 5 May 2015

Assuming, the 'a' matrix has unique values in the first column

for bRow= 1:size(b, 1)

aRow = find(a(:,1)==b(bRow,1), 1);

if ~isempty(aRow)

b(thisrow,2) = a(aRow,2);

end

end

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.