필터 지우기
필터 지우기

for loop with multiple inputs

조회 수: 6 (최근 30일)
Neil Solan
Neil Solan 2018년 2월 4일
답변: Guillaume 2018년 2월 4일
So I know I've done this a million times but it's been a few years since I've used MATLAB and I forget exactly how to go about this. I want to graph two equations as a variable changes, but it doesn't seem to be working. Here's the full problem:
"Graph amplification and phase angle for 0 <= r <= 2.5."
Here's my code:
for r = 0:0.1:2.5
X = (f_0/omega_n^2)/(sqrt((1-r^2)^2+(2*zeta*r)^2)); %Amplification Equation
phi = atan2((2*zeta*r),(1-r^2)); %Phase angle equation
end
However this is giving me a single value for both phase angle and amplification. (All the variables are correctly defined) How do I get it to spit out a matrix with every value for amplification and phase angle between 0 and 2.5? Do I need an if statement?
Thanks in advance.

채택된 답변

Guillaume
Guillaume 2018년 2월 4일
If you use a for loop, you need to index X and phi otherwise you will of course overwrite the previous result. So you could do something like:
r = 0:0.1:2.5;
X = zeros(size(all_r));
phi = zeros(size(all_r));
for idx = 1:numel(r)
X(idx) = (f_0/omega_n^2)/(sqrt((1-r(idx)^2)^2+(2*zeta*r(idx))^2)); %Amplification Equation
phi(idx) = atan2((2*zeta*r(idx)),(1-r(idx)^2)); %Phase angle equation
end
But of course, matlab can operate on whole vectors at once so a loop is not needed at all:
r = 0:0.1:2.5;
X = (f_0/omega_n^2)./(sqrt((1-r.^2).^2+(2*zeta*r).^2)); %Amplification Equation
phi = atan2((2*zeta*r),(1-r.^2)); %Phase angle equation
Note the replacement of / by ./ and ^ by .^ for array operation

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by