How to change values from negative to positive and vicer versa in a loop

5 views (last 30 days)
Dear Everyone;
I have created a for loop to compute certain values. Within the loop if Mw, Mx, My and Mz comes out of as a postive number I want to change it to a negative; and if Mw, Mx, My and Mz comes out of as a negative number I want to change it to a positive.
I have tried to do this with "If Statements", but the set of values come out as all positive or all negative.
Here is my code:
clear, clc, close all
% Distribution factor
DF = [0.4444 0.5556 0.5714 0.4286];
% Starting bending moments
M1 = (-25 + 20)*DF(1);
M2 = (-25 + 20)*DF(2);
M3 = (-20 + 4.67)*DF(3);
M4 = (-20 + 4.67)*DF(4);
for i = 1:8
% carry over
cf1 = M1/2;
cf2 = M2/2;
cf3 = M3/2;
% First distribution
Mw(i) = (0 + cf3)*DF(1)
Mx(i) = (0 + cf3)*DF(2)
My(i) = (0 + cf2)*DF(3)
Mz(i) = (0 + cf2)*DF(4)
% If Mw, Mx, My and Mz is positive change to a negative value
if Mw(i) > 0
Mw(i) = -(Mw(i))
% If Mw, Mx, My and Mz is negative change to a positive value
elseif Mw(i) < 0
Mw(i) = abs(Mw(i))
end
M1 = Mw(i);
M2 = Mx(i);
M3 = My(i);
M4 = Mz(i);
As you can see I have only attempted this with Mw. This is just to practise. Once I get the correct results I will include Mx, My and Mz.
Can someone help please?

Accepted Answer

Voss
Voss on 16 Mar 2025
clear, clc, close all
% Distribution factor
DF = [0.4444 0.5556 0.5714 0.4286];
% Starting bending moments
M1 = (-25 + 20)*DF(1);
M2 = (-25 + 20)*DF(2);
M3 = (-20 + 4.67)*DF(3);
M4 = (-20 + 4.67)*DF(4);
for i = 1:8
% carry over
cf1 = M1/2;
cf2 = M2/2;
cf3 = M3/2;
% First distribution
Mw(i) = -(0 + cf3)*DF(1);
Mx(i) = -(0 + cf3)*DF(2);
My(i) = -(0 + cf2)*DF(3);
Mz(i) = -(0 + cf2)*DF(4);
M1 = Mw(i);
M2 = Mx(i);
M3 = My(i);
M4 = Mz(i);
end
Mw
Mw = 1×8
1.9464 -0.1764 0.1545 -0.0140 0.0123 -0.0011 0.0010 -0.0001
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Mx
Mx = 1×8
2.4334 -0.2205 0.1931 -0.0175 0.0153 -0.0014 0.0012 -0.0001
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
My
My = 1×8
0.7937 -0.6952 0.0630 -0.0552 0.0050 -0.0044 0.0004 -0.0003
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Mz
Mz = 1×8
0.5953 -0.5215 0.0472 -0.0414 0.0038 -0.0033 0.0003 -0.0003
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!