Plotting a matrix in a for loop.

조회 수: 34 (최근 30일)
Rahjee Hajj
Rahjee Hajj 2019년 11월 27일
편집: ME 2019년 11월 27일
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에서 Data Type Identification에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by