for loop does not iterate
显示 更早的评论
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.
采纳的回答
更多回答(2 个)
madhan ravi
2023-11-21
编辑:madhan ravi
2023-11-21
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 个评论
Konrad Suchodolski
2023-11-21
Dyuman Joshi
2023-11-21
编辑:Dyuman Joshi
2023-11-21
"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))
类别
在 帮助中心 和 File Exchange 中查找有关 MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!