Undefined function or variable (h)
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Leora
le 24 Sep 2014
Modifié(e) : John D'Errico
le 24 Sep 2014
I keep getting undefined function or variable h. This is my code to determine Euler's approximation for N=500 and N=5000
f=inline('2*y','t','y')
y(2)=y(1)+h*f(t(1),y(1)), t(2)=t(1)+h,
y(3)=y(2)+h*f(t(2),y(2)), t(3)=t(2)+h,
y(1)=3; t(1)=0; h = 0.1;
for n = 1:5
y(n+1)= y(n)+h*f(t(n),y(n));
t(n+1) = t(n)+h;
end
[t500,y500] = euler(f,[0,.5],3,500);
[t5000,y5000] = euler(f,[0,.5],3,5000);
t = linspace(0,.5,100); y = 3*exp(2*t); % evaluate the exact solution
plot(t500,y500,'ro-',t5000,y5000,'bx-',t,y,'k-'); axis tight;
legend('Euler N = 500','Euler N = 5000','Exact',2);
This is my function file:
function [t,y] = euler(f,tspan,y0,N)
% Solves the IVP y' = f(t,y), y(t0) = y0 in the time interval tspan = [t0,tf]
% using Euler's method with N time steps.
% Input:% f = name of inline function or function M-file that evaluates the ODE
% (if not an inline function, use: euler(@f,tspan,y0,N))
% For a system, the f must be given as column vector.
% tspan = [t0, tf] where t0 = initial time value and tf = final time value
% y0 = initial value of the dependent variable. If solving a system,
% initial conditions must be given as a vector.
% N = number of steps used.
% Output:
% t = vector of time values where the solution was computed
% y = vector of computed solution values.
m = length(y0);
t0 = tspan(1);
tf = tspan(2);
h = (tf-t0)/N; % evaluate the time step size
t = linspace(t0,tf,N+1); % create the vector of t values
y = zeros(m,N+1); % allocate memory for the output y
y(:,1) = y0'; % set initial condition
for n=1:N
y(:,n+1) = y(:,n) + h*f(t(n),y(:,n)); % implement Euler's method
end
t = t'; y = y'; % change t and y from row to column vectors
end
0 commentaires
Réponse acceptée
John D'Errico
le 24 Sep 2014
Modifié(e) : John D'Errico
le 24 Sep 2014
Well, think about it. Line 2 of your code uses the variable h.
Have you ever defined a variable h before that point? MATLAB cannot read your mind to know what it might be.
When you have a problem like this, execute your code ONE line at a time. Then think about the error it gives you. Look at the variables in that line to see what might the error tell you.
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!