If/Else statement within a For loop statement

% OBJ: Clear command window and workspace
clear
clc
% OBJ: Create the vector of angles theta
theta=[-pi/2: pi/100: pi/2];
% OBJ: Calculate gain for each angle theta
for G=[theta];
if theta==0
G=0.5;
else
G=abs((sin(4.*theta))./(4.*theta));
end
end
% OBJ: Create and display a polar plot of G vs. theta
polar(theta,G)
title('Antenna Gain vs. Theta')
The reason I have to do this is to account for the point where theta will equal 0 and leave that data point undefined but idk why the data point remains undefined. When I run the script, everything is correct and the graph looks good, except for that one data point which remains undefined.
There's something wrong syntactically in the loop, but I cannot ascertain what it is. Any help is appreciated.

 Réponse acceptée

First, the easy way:
theta=[-pi/2: pi/100: pi/2];
G=abs((sin(4.*theta))./(4.*theta));
G(theta==0) = 0.5
polar(theta,G)
Second, the reason your loop isn't working is because you redefine G on each iteration. You need to index into the iith element of G
for ii = 1:n
if theta(ii)==0
G(ii) = 0.5
else
G(ii) = stuff_with(theta(ii))
end
end

Plus de réponses (1)

Akash
Akash le 28 Oct 2014

0 votes

Thank you for clearing that up, Sean. As soon as I read that I needed to index into the iith element of G, I understood right away.
Thanks, boss.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by