Calling a function inside another function with iteration

1 回表示 (過去 30 日間)
Jose Sosa Lopez
Jose Sosa Lopez 2020 年 2 月 17 日
編集済み: Jose Sosa Lopez 2020 年 2 月 18 日
Hello community,
I am trying to reproduce a graph, but I guess I have a problem calling a function. Could you help me?
clear all; clc; close all;
c=1;
Yi0=c;
t=linspace(0,10,101);
T=0.1;
k=4;
for ite=2:101
y(ite)=funcion(T,t(ite),Yi(ite-1),k); %(Maybe here I have an error?)
end
plot(t,y')
%%
function Yout=funcion(T,t,Yi0,k)
Yi=zeros(k,1);
Yi(1)=Yi0;
for itek=2:k
for n=1:(k-1)
Yi(itek)=(T/(itek-1))*(Yi(itek-1)-exp(t(ite))*(Yi(n)*Yi(itek-n)));
Yi(itek)=Yi(itek)+Yi(itek-1); %I want to use in my next iteration, for Yi(1)= to the sum of the previous Yi(itek), so I dont know how o put it
end
end
Yout=sum(Yi);
end
the graph should be like this:
  3 件のコメント
Jose Sosa Lopez
Jose Sosa Lopez 2020 年 2 月 17 日
Giuseppe Inghilterra
Giuseppe Inghilterra 2020 年 2 月 17 日
Hi,
in your code there are several errors. Example in following line:
y(ite)=funcion(T,t(ite),Yi(ite-1),k); %(Maybe here I have an error?)
you don't initialize Yi before, thus matlab returns an error.
In following line
Yi(itek)=(T/(itek-1))*(Yi(itek-1)-exp(t(ite))*(Yi(n)*Yi(itek-n)));
when you evaluate exp(t(ite)), the variable "ite" is not defined inside function. Maybe it should be "itek" instead.
In general I advice you to choose more appropriate name variables, in this way you are less error prone.
I finish to run code after these two errors.
Do you have mathematical formulation of the curve that you want to plot? It will be easier check your code.

サインインしてコメントする。

採用された回答

Jose Sosa Lopez
Jose Sosa Lopez 2020 年 2 月 18 日
編集済み: Jose Sosa Lopez 2020 年 2 月 18 日
%https://www.hindawi.com/journals/aaa/2014/486509/#B22
%EMHPM
clear all; clc; close all;
c=1;
yi0=c; %Initial condition
t=linspace(0,10,101); %time interval=0.1
T=0.1;
k=10;
yi=zeros(101,1); yi(1)=yi0;
for itet=2:101
yi(itet)=funcion(0.1,t(itet),yi(itet-1),k);
end
plot(t,yi','--')
hold on
%%
% Function with ode45
t=linspace(0,10,101);
yinicial = 1;
[t,y] = ode45(@(t,y) y-(exp(t))*y^2, t, yinicial);
plot (t,y)
hold off
%%
function Yout=funcion(T,t,Yi0,k)
Yi=zeros(k,1);
Yi(1)=Yi0;
for itek=2:k
for n=1:(itek-1)
Yi(itek)=(T/(itek-1))*(Yi(itek-1)-exp(t)*(Yi(n)*Yi(itek-n)));
end
end
Yout=sum(Yi);
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by