How to change positive/ negative sign of a value in if condition loop ?

조회 수: 8 (최근 30일)
Shiv Karpoor
Shiv Karpoor 2022년 1월 29일
댓글: Shiv Karpoor 2022년 1월 29일
Hello MATLAB Community,
I have problem with my if condition statement.
After finding two values (namely phi & theta) randomly within a certain a range,
I need to also consider a third value (psi) which is the opposite of phi value and perform an iteration using for loop.
In order to do so, I considered "if condition" to say that 'if phi is positive then psi is negative' and 'if phi is negative then psi is positive'.
But when I ran 3 iterations, I wasn't getting what I expected to get.
I got these values for 3 iterations:
first iteration:
phi = 0.0299
theta = -0.3501
psi = -0.0299
second iteration:
phi = 0.1981
theta = 0.2599
psi = -0.1981
third iteration:
phi = -0.5111
theta =-0.1706
psi = -0.5111
As you can see, when phi is negative in third iteration, the psi value is also the same but I want the sign to be opposite.
here is my code:
d2r = pi/180;
g = 30; %upper limit phi
h = -30; %lower limit phi
j = 30; %upper limit theta
l = -30; %lower limit theta
n = 3;
for k = 1:n
phi = (h + (g-h)*rand(1))*d2r %range of limit in phi
theta = (l + (j-l)*rand(1))*d2r %range of limit in theta
if phi > 0
psi = -phi
elseif phi < 0
psi = +phi
end
end
Can anyone please help me with any suggestions.
Thank you in advance!!
I really appreciate your help.
Kind regards,
Shiv

채택된 답변

KSSV
KSSV 2022년 1월 29일
편집: KSSV 2022년 1월 29일
Why you are worried about creating it in a loop with if condition? You create your phi vector and after just change the sign of phi to get psi.
d2r = pi/180;
g = 30; %upper limit phi
h = -30; %lower limit phi
j = 30; %upper limit theta
l = -30; %lower limit theta
n = 3;
phi = zeros(n,1) ;
theta = zeros(n,1) ;
for k = 1:n
phi(k) = (h + (g-h)*rand(1))*d2r ; %range of limit in phi
theta(k) = (l + (j-l)*rand(1))*d2r ; %range of limit in theta
end
psi = -phi ;
[phi psi]
ans = 3×2
-0.0747 0.0747 -0.4408 0.4408 0.4802 -0.4802
If you want to go by yout loop method. You need to follow like shown below.
d2r = pi/180;
g = 30; %upper limit phi
h = -30; %lower limit phi
j = 30; %upper limit theta
l = -30; %lower limit theta
n = 3;
for k = 1:n
phi = (h + (g-h)*rand(1))*d2r ;%range of limit in phi
theta = (l + (j-l)*rand(1))*d2r ; %range of limit in theta
if phi > 0
psi = -phi ;
elseif phi < 0
psi = -phi ; % only a chnage here, as phi is already negative, give minus sign or use abs(phi)
end
[phi psi]
end
  댓글 수: 1
Shiv Karpoor
Shiv Karpoor 2022년 1월 29일
I am new to coding and MATLAB as well, there is no mandate to use the if loop condition.
I just thought it would work and tried it.
But I will keep this in my mind, thank you so much KSSV !! I appreciate your help.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Debugging and Analysis에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by