Simple solution to manuplate matrix

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

 采纳的回答

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 个评论

yes ty i figured it out too thanx for answer i m using this A = [1 5 3 8 9 4 7 6 5 2]; B = [5 2 3 9 7 4 5]; as=size(A); bs=size(B); A1= A([1:as(2)-bs(2)]); C= [A1,B]; same i guess i ll accept your answer
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
oh cool thankyou again.

请先登录,再进行评论。

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by