Save each iteration of a for loop to table

조회 수: 54 (최근 30일)
Emma Stanton
Emma Stanton 2023년 2월 2일
편집: Stephen23 2023년 2월 7일
I'm trying to calculate the roots of a cubic polynomial for several different values. This is the original polynomial, in case that helps:
I'm not confused about getting the coefficients, that isn't the issue. I'm trying to get the roots of alpha for several values of alpha_0, and I want to save them all in one table or matrix so that I can use the data to generate multiple plots.
for alpha_0 = [-1 -0.5 -0.1 0 0.1 0.5 1]
for alpha = zeros()
p = [1 2*alpha_0, alpha_0^2, -1/2];
r = roots(p);
alpha = [; r];
Roots = array2table(alpha)
end
end
This is the code I have currently, but it rewrites my output each time. Could anyone advise on how I can save all roots of alpha for all values of alpha_0 in the one matrix and/or table? Thanks so much!

채택된 답변

Stephen23
Stephen23 2023년 2월 2일
With MATLAB it is invariably easier to loop over indices, rather than looping over data values directly.
V = [-1,-0.5,-0.1,0,0.1,0.5,1];
N = numel(V);
R = nan(3,N);
for k = 1:N % loop over indices
p = [1,2*V(k),V(k)^2,-1/2];
R(:,k) = roots(p);
end
display(R)
R =
1.5652 + 0.0000i 1.1573 + 0.0000i 0.8617 + 0.0000i -0.3969 + 0.6874i -0.4642 + 0.6862i -0.7500 + 0.6614i -1.1486 + 0.6028i 0.2174 + 0.5217i -0.0786 + 0.6526i -0.3309 + 0.6861i -0.3969 - 0.6874i -0.4642 - 0.6862i -0.7500 - 0.6614i -1.1486 - 0.6028i 0.2174 - 0.5217i -0.0786 - 0.6526i -0.3309 - 0.6861i 0.7937 + 0.0000i 0.7285 + 0.0000i 0.5000 + 0.0000i 0.2972 + 0.0000i
  댓글 수: 2
Emma Stanton
Emma Stanton 2023년 2월 7일
Thank you very much!
I'm now trying to separate them into real and imaginary parts. I've tried adding real = real(R) and imag = imag(R) at the end of the code there, but am getting error messages. Do you have any suggestions for this? Your help is much appreciated!
Stephen23
Stephen23 2023년 2월 7일
편집: Stephen23 2023년 2월 7일
"I've tried adding real = real(R) and imag = imag(R) at the end of the code there, but am getting error messages"
Do not use variable names that are the same as the function names.
V = [-1,-0.5,-0.1,0,0.1,0.5,1];
N = numel(V);
R = nan(3,N);
for k = 1:N % loop over indices
p = [1,2*V(k),V(k)^2,-1/2];
R(:,k) = roots(p);
end
R_real = real(R)
R_real = 3×7
1.5652 1.1573 0.8617 -0.3969 -0.4642 -0.7500 -1.1486 0.2174 -0.0786 -0.3309 -0.3969 -0.4642 -0.7500 -1.1486 0.2174 -0.0786 -0.3309 0.7937 0.7285 0.5000 0.2972
R_imag = imag(R)
R_imag = 3×7
0 0 0 0.6874 0.6862 0.6614 0.6028 0.5217 0.6526 0.6861 -0.6874 -0.6862 -0.6614 -0.6028 -0.5217 -0.6526 -0.6861 0 0 0 0

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by