How to calculate all the numbers in an array with some conditions?

1 Ansicht (letzte 30 Tage)
ZIYI WENG
ZIYI WENG am 3 Mär. 2021
Kommentiert: ZIYI WENG am 5 Mär. 2021
I calculated some radian value of angles from the previouse code.
n = 8;
wl = 1;
d = wl./2;
AF = zeros(1,50);
th= 20;
angle_rad = th*pi./180;
phi= (2.*pi.*d .*sin(angle_rad))./wl;
and usd a for loop to display all the numbers of phi
for a = 1:n
AF = (a-1).*phi
end
The problem is I need the value of phi is restricted between-2pi and 2pi. (The angle value (th) I stated was 20 degree but it can be changed, such as -50 degree)
I tried the if elseif statement
for a = 1:n
AF = (a-1).*phi
if AF >= 2.*pi
AF = AF - 2.*pi;
elseif AF <= -2.*pi
AF = AF + 2.*pi;
end
end
It's not working and I am not sure what to do with it, hope to get help from you guys! Thanks!

Antworten (1)

KALYAN ACHARJYA
KALYAN ACHARJYA am 3 Mär. 2021
Bearbeitet: KALYAN ACHARJYA am 3 Mär. 2021
"The problem is I need the value of phi is restricted between-2pi and 2pi. (The angle value (th) I stated was 20 degree but it can be changed, such as -50 degree)"
Case 1: Any value you enter, which is restricted phi within -2pi to + 2pi.
n=8;
wl=1;
d=wl/2;
th=.....%Enter any Value
angle_rad=th*pi/180;
phi=2*pi*d*sin(angle_rad)/wl
Case 2: Or you can limiting such data limiting case using while loop
n=8;
wl=1;
d=wl/2;
while true
th=input('\nPlease Enter the th: ');
angle_rad=th*pi/180;
phi=2*pi*d*sin(angle_rad)/wl;
if phi>=-2*pi && phi<=2*pi
break
else
disp('#Wrong data Input for th')
th=input('\n Re-Enter the th: ');
end
end
Case 3: you can nulify such data, if the condition is fail
  2 Kommentare
ZIYI WENG
ZIYI WENG am 3 Mär. 2021
Thanks for your help!
I am sorry that I did not state my question clealy. The problem is whatever the entering theta is , I will get n values of phi and they stay in the array AF.
for a = 1:n
AF = (a-1).*phi
end
However, since I am calculating angle(phi are angles) The value of phi will be larger than 2pi or smaller than -2pi. That depends on the theta. At the same time, I cannot just abandon the values of phi which out of the range(-2pi to 2pi). I need to change them and control them by keep minus 2pi when the value is over than 2pi until it is smaller or equal to 2pi. On the opposite side, if the value is smaller than -2pi, I need to keep plus 2pi until the value is larger or equals to -2pi.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by