MATLAB Answers

Undefined function or variable 'S', help!

7 views (last 30 days)
Danielle Moore
Danielle Moore on 22 Feb 2016
Commented: Walter Roberson on 22 Feb 2016
I have this function
function z = funct(t,S)
z = 0.4*S-((0.4*S.^2)./10);
and
function euler(func,S0,dt,t0,tf)
% Time interval
t=t0:dt:tf;
% Loop using Euler's method
for i = 1:length(t)-1
S(i+1) = S(i) + dt*(feval(func,t(i),S(i)));
end
t=t'
S=S'
plot(t,S)
xlabel('Time')
ylabel ('S')
when I put this into the command window:
euler(@funct,7,.001,0,25)
I get this error:
Undefined function or variable 'S'.
Error in euler (line 8)
S(i+1) = S(i) + dt*(feval(func,t(i),S(i)));

  1 Comment

Walter Roberson
Walter Roberson on 22 Feb 2016
Instead of using
feval(func, t(i), S(i))
use
func(t(i), S(i))
unless you specifically want to allow the user to pass a function name as a string instead of as a function handle.

Sign in to comment.

Answers (1)

jgg
jgg on 22 Feb 2016
You never define S in your function. You probably want something like this:
function euler(func,S0,dt,t0,tf)
% Time interval
t=t0:dt:tf;
S = zeros(1,length(t)-1)
S(1) = S0;
% Loop using Euler's method
for i = 1:length(t)-1
S(i+1) = S(i) + dt*(feval(func,t(i),S(i)));
end
t=t'
S=S'
plot(t,S)
xlabel('Time')
ylabel ('S')

  0 Comments

Sign in to comment.