How to change positive/ negative sign of a value in if condition loop ?
7 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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]
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Debugging and Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!