Need help to create a loop

4 Ansichten (letzte 30 Tage)
Ajay Guliya
Ajay Guliya am 2 Okt. 2021
Kommentiert: Ajay Guliya am 2 Okt. 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)

Antworten (1)

Alan Stevens
Alan Stevens am 2 Okt. 2021
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 Kommentar
Ajay Guliya
Ajay Guliya am 2 Okt. 2021
Thank you Alan, this works perfectly.

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by