MATLAB: Simple solution to manuplate matrix

matrix manipulation

consider i have matrix A=[1 2 3 4 5 6 7 8 9 ]; B=[9 8 7]; i want to add them in such a way that C= A+B = [1 2 3 4 5 6 ,9 8 7]; i used the for loop but it takes too much processing time wonder if there is qa simple solution to this
as=size(A); bs=size(B); for r= 1: as(2)-bs(2); cs(1,r)=A(1,r); end C=[cs,B];

Best Answer

Hi saif,
From your code example, it appears that you wish only to replace the last three elements of A with the three elements of B. Is that correct? If that is the case, then you could do something like:
C = [A(1:length(A)-length(B)) B];
So in the above, the length(A) returns the number of elements in vector A and length(B) returns the number of elements in vector B. We then copy all of A except for those elements that are to be replaced by B, A(1:length(A)-length(B)) and then use the square brackets to concatenate that result with B.
There are two problems with the above code - it does not handle the case where the length of B is greater than the length of A, and it assumes that both A and B are vectors and not matrices.
Hope that this helps!
Geoff