Save each iteration of a for loop to table

50 views (last 30 days)
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!

Accepted Answer

Stephen23
Stephen23 on 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 Comments
Emma Stanton
Emma Stanton on 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 on 7 Feb 2023
Edited: Stephen23 on 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

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!