for loop does not iterate
Ältere Kommentare anzeigen
I am trying to get used to matlab, but I am stuck.
I'm not able to iterate through my x_roots and separate real roots form complex ones
This is my code:
clear all
close all
syms n
w = @(x) 0.01.*x.^4-0.04.*x.^3+0.02.*x.^2+0.04.*x-0.03;
w_vec = [0.01 0.04 0.02 0.04 0.03];
x = -2:.2:4;
w_y = w(x);
x_roots = roots(w_vec)
x_realroots = [];
for i=x_roots
~round(imag(i))
if (~round(imag(i)))
round(imag(i))
x_realroots = [x_realroots i];
else
continue;
end
end
x_realroots
So yeah, I just wanted to get real roots, but now I'm learning basic matlab.
Please explain to me why i cannot iterate through x_roots.
Akzeptierte Antwort
Weitere Antworten (2)
madhan ravi
am 21 Nov. 2023
Bearbeitet: madhan ravi
am 21 Nov. 2023
x_realroots = x_roots(abs(imag(x_roots)) < 1e-4) % 1e-4 tolerance
Array indices in Matlab must be positive integers (or logical). You are trying to us xroots, a vector of complex numbers as the index in your for loop. Loop using integers instead and use that index to select each element of x_roots.
clear all
close all
syms n
w = @(x) 0.01.*x.^4-0.04.*x.^3+0.02.*x.^2+0.04.*x-0.03;
w_vec = [0.01 0.04 0.02 0.04 0.03];
x = -2:.2:4;
w_y = w(x);
x_roots = roots(w_vec)
x_realroots = [];
% for i=x_roots
for i = 1:numel(x_roots)
% ~round(imag(i))
% if (~round(imag(i)))
if (imag(x_roots(i)) == 0)
% round(imag(i))
% x_realroots = [x_realroots i];
x_realroots = [x_realroots real(x_roots(i))];
else
continue;
end
end
x_realroots
x_realroots2 = real(x_roots(imag(x_roots) == 0))
Note that you don't even need a loop.
Also, if you are just getting started with Matlab, I would highly recommend that you take a couple of hours to go through the free online tutorial: Matlab Onramp
3 Kommentare
Konrad Suchodolski
am 21 Nov. 2023
Dyuman Joshi
am 21 Nov. 2023
Bearbeitet: Dyuman Joshi
am 21 Nov. 2023
"You are trying to us xroots, a vector of complex numbers as the index in your for loop."
@Les Beckham, For loop index values can be anything. Do not confuse them with array indices.
And OP is not trying to use the for loop indices as array indices.
Good point. I had misinterpreted what they were trying to do. Of course, the real "Matlab way" is to not have a loop in the first place.
w_vec = [0.01 0.04 0.02 0.04 0.03];
x_roots = roots(w_vec)
x_realroots2 = real(x_roots(imag(x_roots) == 0))
Kategorien
Mehr zu MATLAB finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!