How do I save values in my loop as a column vector?

68 ビュー (過去 30 日間)
Francesca Maher
Francesca Maher 2020 年 3 月 30 日
コメント済み: Francesca Maher 2020 年 3 月 30 日
I have a loop and I need to save two values (h and err_max) from it into a column vector so that I can make a table. I have been using ' after the variable to transpose the vector so that my table works, but this sometimes causes issues when running the whole file because of other sections i have written. Is there a way to save values from a loop into a column vector without using '?
Side note: My value sol2 saves as a column vector by using sol2(k, : ) but I have tried this on h and it creates a big matrix instead.
I will copy my code here:
for i = 1:16
h = 2^-(i+1);
N = 4/h;
% Initialise variables
k = 0;
sol2 = 0;
for t = 0:h:4
k = k + 1;
sol2(k,:) = 2*(t) - exp(t);
end
w=Euler(a,b,N,alpha,f);
err_ = sol2 - w;
err_abs = abs(err_);
err_max(i) = max(err_abs);
h1(i) = h;
end
table(h1', err_max')
  1 件のコメント
Francesca Maher
Francesca Maher 2020 年 3 月 30 日
Also, just to add: my code isn't running correctly at the moment for err_max

サインインしてコメントする。

採用された回答

Robert
Robert 2020 年 3 月 30 日
You can define the variables as columns before your for-loop:
h1 = zeros(16, 1);
err_max = zeros(16, 1);
By then assigning values to it, the variables remain columns.
  1 件のコメント
Francesca Maher
Francesca Maher 2020 年 3 月 30 日
Thank you! Code now runs how I want it to

サインインしてコメントする。

その他の回答 (1 件)

Peng Li
Peng Li 2020 年 3 月 30 日
You can use h1(:) instead to make hi1 explicitely a column vector. This has a potential risk too if you h1 is actually a matrix as it will force it to reshape to a column vector.
For your code, what is your w like? no idea about your a, b, alpha, f variables.
Your outerloop is not necessary and can be optimized. Or at least, to improve efficiency, you'd better reallocate space for those variables that change size with loop.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by