How to add/subtract elements of 2 matrices to create a new matrix of the same size based upon conditional statements?
4 views (last 30 days)
Show older comments
I have 2 11x11 matrices called Mx and Mxy. I want to add and subtract corresponding elements of each matrix to create a new matrix called Mrx.
I need each element of Mxy to be added or subtracted from the corresponding Mx element based upon if that Mx element is negative or positive. If Mx=0, no addition or subtraction needs to be done and the corresponding element of the new output matrix Mrx will be 0 as well.
The if/else statements below explain what I need. I know I need to indicate that I want all elements of the 11x11 matrices (Mx and Mxy) to be ran through and used. I also think I may need a command that says I want output Mrx to be a 11x11 matrix based on the equations and variables as shown below.. but I am not sure. I thought I might need to add a for loop to do what I need, but again I am not sure.
if Mx < 0
Mrx = Mx - Mxy;
elseif Mx > 0
Mrx = Mx + Mxy;
else
Mrx = 0;
end
0 Comments
Accepted Answer
dpb
on 27 Jan 2018
Edited: dpb
on 27 Jan 2018
Nothing needed but to use the result of the logical array as an addressing expression...
Mrx=Mx; % build the start point; this'll end up unmodified for the ==0 locations...
ix=Mx>0; Mrx(ix)=Mrx(ix)+Mxy(ix); % the >0 elements
ix=Mx<0; Mrx(ix)=Mrx(ix)-Mxy(ix); % the <0 elements
You could get clever with the SIGN function, too...
Mrx=Mx+sign(Mx).*Mxy;
2 Comments
dpb
on 27 Jan 2018
Edited: dpb
on 27 Jan 2018
Ah, yes, problem with typing only...when I started the line, that's why I used the temporary variable because need the result more than once but by the time I got to the end forgot about it already! :) Old age does things like that to one... :(
Fixed up Answer for posterity.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!