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

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?

 Accepted 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]);

1 Comment

Thanks a lot for your reply and for introducing me to linear indexing! Great tool!

Sign in to comment.

More Answers (0)

Categories

Asked:

on 24 Apr 2015

Commented:

on 24 Apr 2015

Community Treasure Hunt

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

Start Hunting!