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!