Filter löschen
Filter löschen

for loop with multiple inputs

6 Ansichten (letzte 30 Tage)
Neil Solan
Neil Solan am 4 Feb. 2018
Beantwortet: Guillaume am 4 Feb. 2018
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.

Akzeptierte Antwort

Guillaume
Guillaume am 4 Feb. 2018
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

Weitere Antworten (0)

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by