How to directly construct a sparse transition probability matrix

7 vues (au cours des 30 derniers jours)
Martine van den Boomen
Martine van den Boomen le 24 Août 2018
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) % here is an error
end
Any help is greatly appreciated!

Réponses (1)

Martine van den Boomen
Martine van den Boomen le 25 Août 2018
Modifié(e) : Martine van den Boomen le 25 Août 2018
I found a solution by using a cell array. It works, and I post the answer as it may be helpful for others, but I am not sure whether my approach is the most efficient one.
Q=spalloc(12,12,8)
out=cell(1,4)
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)
out{i}=[i i; d e ; 0.8 0.2]
end
vecmat = cell2mat(out(1:4))
Q=sparse(vecmat(1,:), vecmat(2,:), vecmat(3,:), 12, 12)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by