How can I create new rows in my table?

2 ビュー (過去 30 日間)
Graham
Graham 2025 年 4 月 22 日
コメント済み: Graham 2025 年 4 月 23 日
Hello I am creating a Euler's Method Calculator that plots and creates a table for the outgoing data. I am new to the tables and when creating my table the table just creates one long row with my data rather than creating new rows. I would like the table to be 2 columns holding all of the data.
f = @(t,y) y - t;
h = 0.01;
y0 = 1;
t0 = 0;
tmax = 1;
n = (tmax-t0)/h;
t(1) = t0;
y(1) = y0;
for i = 1 : n
y(i+1) = y(i) + h * f(t(i), y(i));
t(i+1) = t0 + i * h;
fprintf('y(%.2f) = %.4f\n', t(i+1), y(i+1))
end
plot(t, y)
title('Eulers Method h = 0.1');
xlabel('t')
ylabel('y')
g = table();
g.t = t;
g.y = y;
fig = uifigure;
uit = uitable(fig,"Data",g);

採用された回答

Walter Roberson
Walter Roberson 2025 年 4 月 22 日
編集済み: Walter Roberson 2025 年 4 月 22 日
t(1) = t0;
y(1) = y0;
for i = 1 : n
y(i+1) = y(i) + h * f(t(i), y(i));
t(i+1) = t0 + i * h;
fprintf('y(%.2f) = %.4f\n', t(i+1), y(i+1))
end
You start with a scalar t and y, and you extend them by writing new elements to the vector.
When you start with scalar values and extend the vectors by writing new elements using single indices, then the vectors are created as row vectors
So when you
g = table();
g.t = t;
g.y = y;
You are making g.t and g.y as row vectors . But in order to form proper table entries, they need to be column vectors
The easiest fix is
g.t = t(:);
g.y = y(:);
but you could instead do
t = zeros(n+1,1);
y = zeros(n+1,1);
before initializing t(1) and y(1) -- and doing so would be more efficient.
  1 件のコメント
Graham
Graham 2025 年 4 月 23 日
Thanks so much!

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

その他の回答 (1 件)

dpb
dpb 2025 年 4 月 22 日
編集済み: dpb 2025 年 4 月 23 日
@Walter explained the row orientation, just a very slight recasting to the same end. Almost as easy (ten characthers added instead of six) would be to write
...
for i = 1 : n
y(i+1,1) = y(i,1) + h * f(t(i,1), y(i,1));
t(i+1,1) = t0 + i * h;
...
which will force the column vectors by explicitly writing to first column only.
Alternatively (just a very slight efficiency improvement besides if n is not humongous, in which case it can become noticeable)..."preallocation" is an important concept when it's feasible although for small problems it may be immaterial, getting into the habit is agoodthing™.
t=nan(n+1,1); y=t; % initialize column vectors to nan
t(1) = t0;
y(1) = y0;
for i = 1 : n
y(i+1) = y(i) + h * f(t(i), y(i));
t(i+1) = t0 + i * h;
fprintf('y(%.2f) = %.4f\n', t(i+1), y(i+1))
end
Now, t and y will already be column vectors so then
...
g=table(t,y);
fig = uifigure;
uit = uitable(fig,"Data",g);
There's no need for the struct; uitable supports the MATLAB table class as well.
  1 件のコメント
Graham
Graham 2025 年 4 月 23 日
Thank you!

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

カテゴリ

Help Center および File ExchangeTables についてさらに検索

タグ

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by