Simple solution to manuplate matrix

1 view (last 30 days)
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];

Accepted Answer

Geoff Hayes
Geoff Hayes on 23 Apr 2014
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
  3 Comments
Geoff Hayes
Geoff Hayes on 23 Apr 2014
Hi saif,
Note that if you just want to retrieve the number of columns from a vector, then you can write:
acols = size(A,2);
bcols = size(B,2);
So with the above, you are getting the second dimension from each vector..which happens to be the number of columns. Then you can avoid the as(2)-bs(2) and just replace with acols-bcols.
Geoff

Sign in to comment.

More Answers (0)

Categories

Find more on Function Creation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!