Save each iteration of a for loop to table

52 Ansichten (letzte 30 Tage)
Emma Stanton
Emma Stanton am 2 Feb. 2023
Bearbeitet: Stephen23 am 7 Feb. 2023
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!

Akzeptierte Antwort

Stephen23
Stephen23 am 2 Feb. 2023
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 Kommentare
Emma Stanton
Emma Stanton am 7 Feb. 2023
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 am 7 Feb. 2023
Bearbeitet: Stephen23 am 7 Feb. 2023
"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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by