Dibbs
Dibbs

Reputation: 49

MATLAB: Plot inside a For Loop

Pardon my ignorance here, but I cannot seem to understand how to plot data inside a simple MATLAB for loop. I currently have the following:

sigma=[.9 .9250 .95 .95];
gamma=[1 .0784 .54 .4862];
F=[0 0 .25 0;0 0 0 0;0 0 0 0;0 0 0 0];
for e=0:.01:.2
   R_0=max(eig(F*inv((eye(4)-[sigma(1)*(1-gamma(1)) 0 0 0;...
       sigma(1)*gamma(1) sigma(2)*(1-gamma(2)) 0 0;...
       0 sigma(2)*gamma(2) sigma(3)*(1-gamma(3))*(1-e) sigma(4)*gamma(4);...
       0 0 sigma(3)*gamma(3)*(1-e) sigma(4)*(1-gamma(4))]))))
end 

I am trying to plot R_0 with respect to e. The for loop works in that for each value of e (0, then .01, then .02, up until 2), the code gives me values for R_0 (1.1049, then 1.0138, then .9365, up until .3949). So basically I have a group of points that I am trying to plot and then connect with a line, but I cannot seem to figure out how to plot this.

Once again, this question seems extremely simple, but I would greatly appreciate any help.

Upvotes: 1

Views: 141

Answers (1)

il_raffa
il_raffa

Reputation: 5190

First you have to collect the R_0 values in each iteratiion (in the current version of your code, you are overwritting the value at each iteration).

To save all the value, you have to use R_0 an array and introduce a counter to be incremented in the loop; then you can use the plot function to plot the data.

In the following code you can see:

the initialization of the conter cnt

its increment at each itaration

the use of the plot function after the loop

sigma=[.9 .9250 .95 .95];
gamma=[1 .0784 .54 .4862];
F=[0 0 .25 0;0 0 0 0;0 0 0 0;0 0 0 0];

% Initialize the counter
cnt=0;

for e=0:.01:.2
   % Increment the counter
   cnt=cnt+1;
   % Use R_0 as an array and store the value of each iteration

   R_0(cnt)=max(eig(F*inv((eye(4)-[sigma(1)*(1-gamma(1)) 0 0 0;...
      sigma(1)*gamma(1) sigma(2)*(1-gamma(2)) 0 0;...
      0 sigma(2)*gamma(2) sigma(3)*(1-gamma(3))*(1-e) sigma(4)*gamma(4);...
      0 0 sigma(3)*gamma(3)*(1-e) sigma(4)*(1-gamma(4))]))))
end
% Plot the results
plot([0:.01:.2],R_0,'o-')

enter image description here

Hope this helps,

Qapla'

Upvotes: 2

Related Questions