How can I create new rows in my table?

2 次查看(过去 30 天)
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 个)

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.

类别

Help CenterFile Exchange 中查找有关 Tables 的更多信息

标签

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by