Dear community,
I am new to Matlab. I am trying to construct a sparse probability transition matrix. A small example of the full probability transition matrix is matrix P. Matrix A represents my states and the row number gives an index for a particular state.
For the first four source states in matrix A, I search in the same matrix for the index of their corresponding destination states based on some conditions.
The indices of a source state and in this case two destination states, provide the row and column indices for my probability transition matrix P.
My first question is: is this approach with using find the most time-efficient one?
My second question is: how can I directly construct a sparse probability transition matrix Q? In my current code the loop does not work for Q. Q should look like:
Q =
(1,5) 0.8000
(2,6) 0.8000
(3,7) 0.8000
(1,8) 0.2000
(4,8) 0.8000
(2,9) 0.2000
(3,10) 0.2000
(4,11) 0.2000
My code for constructing full matrix P:
A = [1 1 1 ; 1 1 2; 1 2 1; 1 2 2;...
2 1 1 ; 2 1 2 ; 2 2 1; 2 2 2;...
2 2 3 ; 2 3 2 ; 2 3 3; 3 3 3]
P = zeros(12,12)
for i = 1:4
a=A(i,1)
b=A(i,2)
c=A(i,3)
d = find(A(:,1)==a+1 & A(:,2)==b & A(:,3)==c)
e = find(A(:,1)==a+1 & A(:,2)==b+1 & A(:,3)==c+1)
P(i,d)=0.8
P(i,e)=0.2
end
Followed by my attempt to directly construct a sparse matrix Q instead of full matrix P:
Q=spalloc(12,12,8)
for i = 1:4
a=A(i,1)
b=A(i,2)
c=A(i,3)
d = find(A(:,1)==a+1 & A(:,2)==b & A(:,3)==c)
e = find(A(:,1)==a+1 & A(:,2)==b+1 & A(:,3)==c+1)
Q=sparse(i, [d e], [0.8 0.2], 12, 12)
end
Any help is greatly appreciated!