Plotting a matrix in a for loop.

21 次查看(过去 30 天)
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?

采纳的回答

ME
ME 2019-11-27
编辑:ME 2019-11-27
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.

更多回答(1 个)

Bob Thompson
Bob Thompson 2019-11-27
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 个评论
ME
ME 2019-11-27
编辑:ME 2019-11-27
Can't believe how similar our answers are and how closely timed either!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Markov Chain Models 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by