Return the final x for different t

1 Ansicht (letzte 30 Tage)
Phong Pham
Phong Pham am 6 Aug. 2012
I tried to create Runge Kutta 4 order method with 2 matlab files:
1) function [fv]=evalfunc(t,x)
fv=4.0*exp(0.8*t)-x/2.0;
2) close all clear all
a=0;
b=4;
N=25;
h=(b-a)/N;
t=[a:h:b];
x(1)=2;
for i=1:N
k1 = h*evalfunc(t(i),x(i));
k2 = h*evalfunc(t(i)+h/2,x(i)+k1/2);
k3 = h*evalfunc(t(i)+h/2,x(i)+k2/2);
k4 = h*evalfunc(t(i)+h,x(i)+k3);
x(i+1) =x(i) + (k1 + 2*k2 + 2*k3 + k4)/6;
t(i+1) = a + h*i;
end
A= [t,x];
plot (t,x)
I want to return the result of x(i+1) for every t. Do I just type [t,x]?
How to get t,x result in column of vector ? because when i run the matlab it shown column 1...34 in command window.

Akzeptierte Antwort

John Petersen
John Petersen am 6 Aug. 2012
Matlab defaults to rows. So when creating a vector on the fly like you have, specify both row and column. These lines should be
x(i+1,1) =x(i) + (k1 + 2*k2 + 2*k3 + k4)/6;
t(i+1,1) = a + h*i;
to give you columnwise vectors. Alternatively, you could reassign them
x=x(:);
t=t(:);
at the end of the function.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by