How can I create new rows in my table?
5 views (last 30 days)
Show older comments
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);
0 Comments
Accepted Answer
Walter Roberson
on 22 Apr 2025
Edited: Walter Roberson
on 22 Apr 2025
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.
More Answers (1)
dpb
on 22 Apr 2025
Edited: dpb
on 23 Apr 2025
@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);
See Also
Categories
Find more on Tables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!