Wanting to + inside an if statement once a variable reaches 1, not sure how to do it?

1 view (last 30 days)
Joe Selfridge
Joe Selfridge on 20 Apr 2022
Answered: Cris LaPierre on 20 Apr 2022
I want to increase my phi by 180 if the variable r>=1. I decided to use an if statement for this why is it not working?
%%%%%%%%%%undamped system
clc
clear all
k=321; %spring constant
c=10.2; %damper
m=1.27; %mass
F0=10;
omega=linspace(0,3,1000);
x0=0.05; %little x0
deltax=0.75; %little xdot 0
omegaN=1;
deltast=F0/k; %this is the squiggle st one
zeta=[0,0.5,1,2,3,4.5,5]; %zeta damping ratio
r=omega/omegaN;
for n=1:7;
phi=atand((2*zeta(n).*r)./(1-r.^2));
if r>=1;
phi= phi+180;
else
phi=phi+0;
end
plot(r,phi);
xlabel('Frequency ratio')
ylabel('phase angle degrees')
hold on
end
hold off
legend('zeta1','zeta2','zeta3','zeta4','zeta5','zeta6','zeta7')

Answers (2)

Alok Kumar
Alok Kumar on 20 Apr 2022
because, r is a vector with 1000 elements, you need to check every entry in the array for the condition, try this;
%%%%%%%%%%undamped system
clc
clear;close;
k=321; %spring constant
c=10.2; %damper
m=1.27; %mass
F0=10;
omega=linspace(0,3,1000);
x0=0.05; %little x0
deltax=0.75; %little xdot 0
omegaN=1;
r= omega/omegaN;
for n=1:7
phi=atand((2*zeta(n).*r)./(1-r.^2));
for i=1:length(r)
if r>= 1
phi= phi+180;
else
phi=phi+0;
end
end
plot(r,phi);
xlabel('Frequency ratio')
ylabel('phase angle degrees')
hold on
end
hold off
legend('zeta1','zeta2','zeta3','zeta4','zeta5','zeta6','zeta7')

Cris LaPierre
Cris LaPierre on 20 Apr 2022
The reason is that r is a vector. The conditional statement of an if statement is not elementwise, meaning that it only executes if all conditions of r are >=1. If even 1 is not, then the else code executes.
A better way to write this condition so the behavior is clear is: if all(r>=1);
I think what you may want to do here is use logical indexing to conditionally change the value of phi for specific elements. You can learn more about logical arrays in Ch 11 of MATLAB Onramp.
k=321; %spring constant
c=10.2; %damper
m=1.27; %mass
F0=10;
omega=linspace(0,3,1000);
x0=0.05; %little x0
deltax=0.75; %little xdot 0
omegaN=1;
deltast=F0/k; %this is the squiggle st one
zeta=[0,0.5,1,2,3,4.5,5]; %zeta damping ratio
r=omega/omegaN;
for n=1:7;
phi=atand((2*zeta(n).*r)./(1-r.^2));
% use logical indexing to modify phi where r>=1
phi(r>=1)= phi((r>=1))+180;
plot(r,phi);
xlabel('Frequency ratio')
ylabel('phase angle degrees')
hold on
end
hold off
legend('zeta1','zeta2','zeta3','zeta4','zeta5','zeta6','zeta7')

Community Treasure Hunt

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

Start Hunting!