Save each iteration of a for loop to table
43 ビュー (過去 30 日間)
古いコメントを表示
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!
0 件のコメント
採用された回答
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)
2 件のコメント
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_imag = imag(R)
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!