Why isn't my matrix being filled?

2 次查看(过去 30 天)
Coby Juarez
Coby Juarez 2021-10-16
编辑: C B 2021-10-16
The intention of this funtion is to be able to give an amount of days and populations for Immune, Sick, and Well people and the function should ouput a matrix with the new population values. Sadly, the function only works for the first two days with the following columns being all zeros. Any tips for me? I'm a beginner
function PopAfterT(t,I0,S0,W0)
populations=zeros(3,t)
populations(:,1)=[I0;S0;W0]
I=zeros(1,t)
I(1,1)=I0
S=zeros(1,t)
S(1,1)=S0
W=zeros(1,t)
W(1,1)=W0
for day=(2:t)
populations(1,day)=I(1,(day-1))+(S(1,(day-1))*.12)-(I(1,day-1)*.01)
populations(2,day)=S(1,(day-1))+(W(1,(day-1))*.08)-(S(1,(day-1))*.04)-(S(1,(day-1))*.02)-(S(1,(day-1))*.12)
populations(3,day)=W(1,(day-1))+(W(1,(day-1))*.06)+(S(1,(day-1))*.02)-(W(1,(day-1))*.02)-(W(1,(day-1))*.08)+(I(1,day-1)*.03)
end
  2 个评论
John D'Errico
John D'Errico 2021-10-16
Do you understand that if you do not return a variable from that function, then nothing changes in your workspace?
Coby Juarez
Coby Juarez 2021-10-16
@John D'Errico I thought I did but your question makes me feel like I do not. Can you elaborate and help me fix it please?

请先登录,再进行评论。

回答(2 个)

C B
C B 2021-10-16
编辑:C B 2021-10-16
@Coby Juarez Its because you are using old values of I S W but you are not updating them in loop.
Please have a look at below code where i have updated I S W i hope answer is correct.
function populations = PopAfterT(t,I0,S0,W0)
populations=zeros(3,t);
populations(:,1)=[I0;S0;W0];
I=zeros(1,t);
I(1,1)=I0;
S=zeros(1,t);
S(1,1)=S0;
W=zeros(1,t);
W(1,1)=W0;
for day=(2:t)
I(day)=I(1,(day-1))+(S(1,(day-1))*.12)-(I(1,day-1)*.01);
S(day)=S(1,(day-1))+(W(1,(day-1))*.08)-(S(1,(day-1))*.04)-(S(1,(day-1))*.02)-(S(1,(day-1))*.12);
W(day)=W(1,(day-1))+(W(1,(day-1))*.06)+(S(1,(day-1))*.02)-(W(1,(day-1))*.02)-(W(1,(day-1))*.08)+(I(1,day-1)*.03);
populations(1,day)=I(day);
populations(2,day)=S(day);
populations(3,day)=W(day);
end
Output = PopAfterT(10,4,5,6)
Output =
4.0000 4.5600 5.0640 5.5214 5.9402 6.3267 6.6864 7.0238 7.3428 7.6465
5.0000 4.5800 4.2340 3.9494 3.7159 3.5249 3.3693 3.2434 3.1424 3.0623
6.0000 5.9800 5.9692 5.9670 5.9730 5.9866 6.0074 6.0351 6.0693 6.1096

DGM
DGM 2021-10-16
编辑:DGM 2021-10-16
When you define a function, you need to describe its input arguments and output arguments.
This function definition has no inputs and no outputs
function mybeep()
beep
end
This function definition adds two numbers and returns a single result.
function c = addtwonumbers(a,b)
c = a+b;
end
I'm assuming that the output is supposed to be the populations variable, so
function populations = PopAfterT(t,I0,S0,W0)
% ...
end

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by