How to write a program to solve a difference equation in Matlab?
이전 댓글 표시
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
John D'Errico
2015년 12월 7일
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
2015년 12월 7일
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.
답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Mathematics에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!