Need help to create a loop

조회 수: 1(최근 30일)
Ajay Guliya
Ajay Guliya 2021년 10월 2일
댓글: Ajay Guliya 2021년 10월 2일
In the code below, I am finding the value of Q for all values of k. Instead of finding value of Q one by one, is there a more efficient way of doing it using a loop?
e=2.7183;
gamma=0.1333;
k = [1,9,23,7,23,9,20,29,63,102,73,59,27,130,75,185,70,92,326]
Rt=0:0.01:10;
P = zeros(length(k)-1,length(Rt));
for i = 1:length(k)-1
lambda = k(i)*exp(gamma*(Rt-1));
P(i,:) = ((lambda.^k(i+1)).*exp(-lambda))/factorial(k(i+1));
P(i,:) = P(i,:) / sum(P(i,:));
end
Q2 = P(1,:).*P(2,:)
Q2 = Q2 /sum(Q2)
Q3 = P(1,:).*P(2,:).*P(3,:)
Q3 = Q3 /sum(Q3)
Q4 = P(1,:).*P(2,:).*P(3,:).*P(4,:)
Q4 = Q4 /sum(Q4)
Q5 = P(1,:).*P(2,:).*P(3,:).*P(4,:).*P(5,:)
Q5 = Q5 /sum(Q5)
plot(Rt,Q2,Rt,Q3,Rt,Q4,Rt,Q5)

답변(1개)

Alan Stevens
Alan Stevens 2021년 10월 2일
How about:
e=2.7183;
gamma=0.1333;
k = [1,9,23,7,23,9,20,29,63,102,73,59,27,130,75,185,70,92,326];
Rt=0:0.01:10;
P = zeros(length(k)-1,length(Rt));
for i = 1:length(k)-1
lambda = k(i)*exp(gamma*(Rt-1));
P(i,:) = ((lambda.^k(i+1)).*exp(-lambda))/factorial(k(i+1));
P(i,:) = P(i,:) / sum(P(i,:));
if i==1
Q(i,:) = P(i,:);
end
if i>1
Q(i,:) = Q(i-1,:).*P(i,:);
end
end
for i = 2:5
Q(i,:) = Q(i,:)/sum(Q(i,:));
end
figure
plot(Rt,Q(2,:),Rt,Q(3,:),Rt,Q(4,:),Rt,Q(5,:))
  댓글 수: 1
Ajay Guliya
Ajay Guliya 2021년 10월 2일
Thank you Alan, this works perfectly.

댓글을 달려면 로그인하십시오.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by