MATLAB Answers

change one column of matrix

13 views (last 30 days)
Na
Na on 28 Jul 2019
Commented: Walter Roberson on 28 Jul 2019
I have A
A=[1,0,4,0,5,0;0,1,0,3,-1,0;0,4,0,0,0,8];
B=[1.2,-1,-2.1,-1.3,-1.4,1;-2.1,1.3,-1,-2,-3,-1.8;1.9,-1.2,3.1,2.7,2.5,-0.5];
index=2;
I want to add nonzero element in A to corresponding B element.
A(index,:)=B(index,A(index, :)~=0)+A(index, :);
result should be
A=[1,0,4,0,5,0; 0, 1+1.3,0,3-2,-1-3,0; 0,4,0,0,0,8];

  0 Comments

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 28 Jul 2019
mask = A(index, :) ~= 0;
A(index, mask) = A(index, mask) + B(index, mask) ;

  3 Comments

Na
Na on 28 Jul 2019
if index=[2;3;4]
A=[1,0,4,0,5,0;0,1,0,3,-1,0;0,4,0,0,0,8; 1,0,4,0,5,0;0,1,0,3,-1,0;0,4,0,0,0,8];
B=[1.2,-1,-2.1,-1.3,-1.4,1;-2.1,1.3,-1,-2,-3,-1.8;1.9,-1.2,3.1,2.7,2.5,-0.5 ;1.2,-1,-2.1,-1.3,-1.4,1;-2.1,1.3,-1,-2,-3,-1.8;1.9,-1.2,3.1,2.7,2.5,-0.5];
index=[2;3;4];
mask = A(index, :) ~= 0;
A(index, mask) = A(index, mask) + B(index, mask) ;
I have this error
The logical indices in position 2 contain a true value outside of the
array bounds.
Na
Na on 28 Jul 2019
I use this one but it makes program slow, if the size of A is big. Is there any better way?
mask = A(index, :) ~= 0;
for i=1:size(mask,1)
A(index(i), mask(i,:)) = A(index(i), mask(i,:)) + B(index(i), mask(i,:)) ;
end
Walter Roberson
Walter Roberson on 28 Jul 2019
Andrei's solution looks good.

Sign in to comment.

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 28 Jul 2019
A(index,:) = A(index,:) + B(index,:).*(A(index,:) ~= 0);

  0 Comments

Sign in to comment.

Sign in to answer this question.