MATLAB: Substitute different number of values in columns of a matrix from other matrix

matrix substitute different values columns rows

I am trying to fill in a matrix with values from other matrix, column-wise in my case. Each column of values has a different number of values. For example, for matrixes
A=[1 2 3;
4 5 6;
7 8 9]
B=[0 7 8;
6 8 9;
0 1 3]
I would like to substitute in A the bottom two numbers of first column, the bottom one in second column and the three of them in third on for the ones in matrix B. The result would be:
A=[1 2 8;
6 5 9;
0 1 3]
I know how to do it using loops but I'm sure that there is a more efficient way of doing it. Any ideas?

Best Answer

  • You can do this all in one operation, using linear indexing:
    idx = [2 3 6 7 8 9];
    A(idx) = B(idx);
    You could do it in one line:
    A([2 3 6 7 8 9]) = B([2 3 6 7 8 9]);