MATLAB: Copy matrix column with refer to secondary column.

column checkingcolumn copyMATLAB

Hi, i have a question as following. Since I am a newbie, I am not familiar with the matrix / cells operation. I wanted to paste the 4th column of matrix B to matrix A with the reference of column 1 or column 2.
For example, >> A=[1,2,3,0;4,5,6,0;7,8,9,0]
A =
1 2 3 0
4 5 6 0
7 8 9 0
>> B=[4,5,6,3]
B =
4 5 6 3
Desired output would be: >> C = [1,2,3,0;4,5,6,3;7,8,9,0]
C =
1 2 3 0
4 5 6 3
7 8 9 0
Is there any simpler and elegant way of doing it instead of relying on FOR loop?

Best Answer

A = [1,2,3,0; 4,5,6,0; 7,8,9,0];
B = [4,5,6,3];
A(ismember(A(:,1:end-1),B(1:end-1),'rows'),end) = B(end);