How to write a program to solve a difference equation in Matlab?
Show older comments
We want to write a program in MATLAB for the function: p(t+1) = f_alpha(p(t)) = alpha*p(t)*e^(-p(t)), alpha > 0. The program has to plot for a given value of alpha and initial population density p0 the solution p of the function versus time t.
function function(alpha,x)
t=1000;
y=zeros(t,1);
y(1)=x;
if alpha >0
hold on;
for j=2:t;
y(j)=alpha*y(j-1)*exp(-y(j-1));
end
hold off;
n=1:t
plot(n,y);
else
fprintf('alpha has to be positive')
end
or
function function(alpha,n)
if a>0
x=n:0.001:10
f=@x a*x.*exp(-x);
hold on;
plot(x,f(x));
hold off;
xlabel('time');
ylabel('population');
hold off;
else
fprintf('alpha has to be positive.')
end
We don't know which one is better and how we can complete the program.
2 Comments
John D'Errico
on 7 Dec 2015
Um, neither is better. Neither will work. You cannot call a function with the name function. In the second, you use a, but pass in alpha. Lots of other problems.
Torsten
on 7 Dec 2015
The first version looks correct, the second looks wrong to me .
But don't call a function "function". And don't plot inside the function where you compute y, but in the calling program. Make y an output of your "function".
Best wishes
Torsten.
Answers (0)
Categories
Find more on Mathematics 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!