Hello, I'm bad at MATLAB but am trying to get better. I had an assignment where I was supposed to solve a system of equations using the Forward Euler method and plot over time. I had never used cells before and my partner got that portion working. I spent a bunch of time reading through help files and this forum and I still don't understand how to implement cells well. I think I'm getting confused with how I should be writing to and reading from cells.
Code:
u(1) = 1; v(1) = 0;
dt = .01;
n = 1;
t = 0:dt:10;
A = [-1 -1;1 -1];
I = [1 0;0 1];
Y = cell (size(t));
u1 = 1; v1 = 0;
Y1 = [u1 ; v1];
Y{n} = [u(n) ; v(n)];
while n <= numel(t)-1
Y{n+1} = (I+dt*A)*Y{n};
n = n+1;
end
Y = Y(1,:);
Ytograph=zeros(size(Y));
for idx=1:numel(Y)
Temp=Y{idx};
Ytograph(idx)=Temp(2);
end
plot(t, Ytograph)
It think it gets messy after the while loop and I'm hoping to get some tips on how to make it better/more efficient.
Thank you!

 Akzeptierte Antwort

Bruno Luong
Bruno Luong am 7 Nov. 2020

0 Stimmen

Convert to array like this after the while loop
Ya = cell2mat(Y);
Ytograph = Ya(2,:);
plot(t, Ytograph)
Yead you guys just make a mistake using CELL when it's not needed.

2 Kommentare

Zachary Miller
Zachary Miller am 7 Nov. 2020
Thanks Bruno. I think I see what you're saying!
Bruno is right, but it takes a minute to see why, and if you want to learn about cell arrays, it worth figuring this out. This
Y{n+1} = (I+dt*A)*Y{n}
is storing a 2x1 double in each cell. This
Y = Y(1,:);
doesn't actually do anything because Y is 1xM. Then this
Ytograph(idx)=Temp(2)
gabs all the 2nd values of each 2x1 in Y. So you could have made Y a 2xM double, and then Ytograph would just be Y(2,:). That would be better code, but you'd need to fiddle a bit with some of the preallocation and indexing.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by