# Need help to create a loop

2 views (last 30 days)
Ajay Guliya on 2 Oct 2021
Commented: Ajay Guliya on 2 Oct 2021
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)

Alan Stevens on 2 Oct 2021
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,:))
Ajay Guliya on 2 Oct 2021
Thank you Alan, this works perfectly.