Plotting a matrix in a for loop.

34 vues (au cours des 30 derniers jours)
Rahjee Hajj
Rahjee Hajj le 27 Nov 2019
Modifié(e) : ME le 27 Nov 2019
Hello community,
I'm new to Matlab and having trouble figuring out how to plot a matrix.
I made a transition matrix that is a markov chain, and I'm given a state vector. Im supposed to perform 31 steps of the markov chain, and on a single figure plot the probability of being in each state at a given iteration. My data is this so far:
SEI = [0.7 0.4 0 0.2 0 0; 0.3 0 0 0 0 0; 0 0.3 0 0 0 0; 0 0.3 1 0.8 0 0; 0 0 0 0 0.25 0; 0 0 0 0 0.75 1];
x0 = [1;0;0;0;0;0];
for i = 1:31
xk =(SEI^i)*x0;
end
where "xk" would be the resulting probability at each step. How do I plot this inside the for loop?

Réponse acceptée

ME
ME le 27 Nov 2019
Modifié(e) : ME le 27 Nov 2019
You have a couple of options here. One is that you store all of the steps of the Markov chain during the for loop and then plot them afterwards - something like this:
SEI = [0.7 0.4 0 0.2 0 0; 0.3 0 0 0 0 0; 0 0.3 0 0 0 0; 0 0.3 1 0.8 0 0; 0 0 0 0 0.25 0; 0 0 0 0 0.75 1];
x0 = [1;0;0;0;0;0];
for i = 1:31
xk(i) =(SEI^i)*x0;
end
plot([1:31],xk(:))
or alternatively, if you have to plot inside the for loop then you can do this as
SEI = [0.7 0.4 0 0.2 0 0; 0.3 0 0 0 0 0; 0 0.3 0 0 0 0; 0 0.3 1 0.8 0 0; 0 0 0 0 0.25 0; 0 0 0 0 0.75 1];
x0 = [1;0;0;0;0;0];
figure; hold on;
for i = 1:31
xk =(SEI^i)*x0;
plot(i,xk,'.b');
end
I'm having a bit of a blank as to how you could get those points to join up into a single line but if the dots (or other symbol of your choosing) will do then this should work.

Plus de réponses (1)

Bob Thompson
Bob Thompson le 27 Nov 2019
With MATLAB you don't really want to perform the plot inside the loop in this case. Just save your results in a matrix and plot once afterwards.
for i = 1:31
xk(i) =(SEI^i)*x0; % Index the results to an element of a matrix
end
plot((1:31),xk)
  1 commentaire
ME
ME le 27 Nov 2019
Modifié(e) : ME le 27 Nov 2019
Can't believe how similar our answers are and how closely timed either!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Data Type Identification dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by