Why isn't my matrix being filled?

조회 수: 11 (최근 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에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by