How to vectorize a function that calculates the joint stochastic matrix from individual different sized matrices to increase speed?

I'm writing a code that calculates the joint probability stochastic matrix of 5 random variables which each have their own stochastic matrices (all my random variables describe Markov chains) which vary in dimensions and may be different depending on specific conditions. I've included a toy example code with 3 random variables below which is a super simplification of the problem (in this example A,B,C are independent--I have dependencies in the real code).
The matrices probA, probB, probC, have been shown for small dimensions, whereas I have much larger sized matrices. I would like to know I how I would vectorize the code so as to increase speed especially since the combinations are in formatted in cells.
probA = [.2 .8; .5 .5];
%A_states = {'H', 'T'};
A_states = {'Heads', 'Tails'};
probB = [.3 .4 .3 ; .6 .2 .2; .1 .5 .4];
%B_states = {'A', 'B', 'C'};
B_states = {'Apples', 'Bananas', 'Carrots'};
probC = [.1 .1 .1 .7; .4 .4 .1 .1; .5 0 .3 .2; .3 .3 0 .4];
C_states = {'1', '2', '3', '4'};
%%%the above information will likely be from file loaded separately as a vector
%%%of structs
%size = length(A_states)*length(B_states)*length(C_states);
matrix_size = length(A_states)*length(B_states)*length(C_states);
combinations=cell(1,matrix_size);
%writing out all possible combinations of A,B,C states
%%%this is done via a function
count=0;
for ii=1:length(A_states)
for jj=1:length(B_states)
for kk=1:length(C_states)
count=count+1;
%combinations{1,count} = [A_states{1,ii};B_states{1,jj};C_states{1,kk}];
combinations{1,count} = [A_states(1,ii);B_states(1,jj);C_states(1,kk)];
end
end
end
%building the joint stochastic matrix from the individual matrix
%%%this is done via a function
probABC = zeros(matrix_size);
for nn=1:count
A_i1 = find(strcmp(A_states, combinations{1,nn}(1,1)));
B_i1 = find(strcmp(B_states, combinations{1,nn}(2,1)));
C_i1 = find(strcmp(C_states, combinations{1,nn}(3,1)));
for mm=1:count
A_i2 = find(strcmp(A_states, combinations{1,mm}(1,1)));
B_i2 = find(strcmp(B_states, combinations{1,mm}(2,1)));
C_i2 = find(strcmp(C_states, combinations{1,mm}(3,1)));
if probA(A_i1,A_i2)~=0 || probB(B_i1,B_i2)~=0 || probC(C_i1,C_i2)~=0
probABC(nn,mm) = probA(A_i1,A_i2)*probB(B_i1,B_i2)*probC(C_i1,C_i2);
end
end
end
%double check that the sum of the rows of probABC equal 1.
sum(probABC,2)

Answers (1)

If all your states are single character strings, you would be better off using plain array of characters instead of cell arrays.
In any case, you certainly don't need loops to generate your combinations or probABC. Your first step is to produce the cartesian product of the steps. This is easily achieved with ndgrid. The cell arrays complicate things a bit though:
[c, b, a] = ndgrid(1:numel(C_states), 1:numel(B_states), 1:numel(A_states)); %in this order to produce the same ordering as your code.
combinations = num2cell(cell2mat([A_states(a(:)); B_states(b(:)); C_states(c(:))]), 1) %works even if states are several characters
The same, using plain arrays of char:
A_states = 'HT';
B_states = 'ABC';
C_states = '1234'
[c, b, a] = ndgrid(C_states, B_states, A_states);
combinations = [a(:), b(:), c(:)]' %simpler!
Your probability matrix is another cartesion product, so another round of ndgrid. Since your original code assumes that the state strings are single characters, I'm going with plain arrays of chars. I'm using lookups through the combinations array, just as you did:
[prows, pcols] = ndgrid(1:size(combinations, 2));
[~, parowloc] = ismember(combinations(1, prows), A_states);
[~, pbrowloc] = ismember(combinations(2, prows), B_states);
[~, pcrowloc] = ismember(combinations(3, prows), C_states);
[~, pacolloc] = ismember(combinations(1, pcols), A_states);
[~, pbcolloc] = ismember(combinations(2, pcols), B_states);
[~, pccolloc] = ismember(combinations(3, pcols), C_states);
probABC = probA(sub2ind(size(probA), parowloc, pacolloc)) .* probB(sub2ind(size(probB), pbrowloc, pbcolloc)) .* probC(sub2ind(size(probC), pcrowloc, pccolloc));
%reshape to recover the shape lost by ismember:
probABC = reshape(probABC, size(prows))

3 Comments

Hi Guillaume,
Thank you for your prompt reply and the pointing out the shadowing mistake. In the toy problem I represented the states as single character strings, but in my real problem the strings are actually full words. This would be akin to:
A_states={'Heads', 'Tails'};
B_states={'Apples', 'Bananas', 'Carrots'};
C_states={'1', '2', '3', '4'};
Actually, in the real problem the states may be similar, like the words 'the', 'there', 'therefore' but still unique which makes their representation as single character strings tricky.
**I've commented out the original code and added the changes to make it easier to see the clarification.
Anyway, given this new information, how would I go about vectorizing without plain arrays of char? cell2mat has issues with dimensions in this case.
In your original code, you concatenated your states into a single string and that is why I had a cell2mat code. I was slightly wrong in that my code worked even if states were several characters only if they were all the same length.
No matter, you're no concatenating into a cell array or cell arrays, so the cell2mat is not needed anymore:
[c, b, a] = ndgrid(1:numel(C_states), 1:numel(B_states), 1:numel(A_states)); %in this order to produce the same ordering as your code.
combinations = num2cell([A_states(a(:)); B_states(b(:)); C_states(c(:))], 1) %works even if states are several characters and different lengths
Note that I probably wouldn't even bother with the num2cell call, and just have a numstates x numcomb cell array:
combinations = [A_states(a(:)); B_states(b(:)); C_states(c(:))];
If you keep the num2cell, it will have to be reversed for the next phase:
combinations = [combinations{:}]; %not needed if num2cell is not used
You can then use the code I wrote previously in my answer to generate probABC.
Hi Guillame,
Once again, thank you for this exchange--I am learning a great deal. I would like to further my question to change the toy problem to a problem which includes dependencies similar to what I am using in my main problem (which has a large number of states). I know that I can adapt it using ndgrid especially for the combinations part (I think I would still need a loop to go through A one by one and then concatenate the final combinations?) and eliminate strcmp as you showed earlier, but now I am mainly worried about how I would go about doing the cartesian product to calculate the probability. Here is the new code given the dependencies:
probA = [.2 .8; .5 .5];
A_states = {'Heads', 'Tails'};
%if A_states switches H->T or T->H use the the stationary distribution of
%B_states_tails or B_states_heads as the initial distribution
probB_heads = [.3 .4 .3 ; .6 .2 .2; .1 .5 .4]; %P(B'|B,A='Heads')
B_states_heads = {'Apples', 'Bananas', 'Carrots'};
limit_dist_heads=limitdist(probB_heads);
probB_tails = [.5 .5; .75 .25]; %P(B'|B,A='Tails');
B_states_tails = {'Pineapples', 'Guavas'};
limit_dist_tails=limitdist(probB_tails);
probC = [.1 .1 .1 .7; .4 .4 .1 .1; .5 0 .3 .2; .3 .3 0 .4];
C_states = {'1', '2', '3', '4'};
%preallocation
matrix_size=(length(B_states_heads)+length(B_states_tails))*length(C_states);
combinations=cell(1,matrix_size);
count=0;
%writing out all possible combinations of A,B states
for ii=1:length(A_states)
if strcmp(A_states(1,ii),'Heads')
for jj=1:length(B_states_heads)
for kk=1:length(C_states)
count=count+1;
combinations{1,count}=[A_states(1,ii);B_states_heads(1,jj);C_states(1,kk)];
end
end
else
for jj=1:length(B_states_tails)
for kk=1:length(C_states)
count=count+1;
combinations{1,count}=[A_states(1,ii);B_states_tails(1,jj);C_states(1,kk)];
end
end
end
end
%P(A'B'C'|ABC)=P(A'B'C'ABC)/P(ABC) =
%=P(A'|B'C'ABC)*P(B'C'ABC)/P(ABC)
%=P(A'|A)*P(B'|C'ABC)P(C'ABC)/P(ABC)
%=P(A'|A)P(B'|B,A)P(C'|ABC)P(ABC)/P(ABC)
%=P(A'|A)P(B'|B,A)*P(C'|C)
%building the joint stochastic matrix from the individual matrix
%%%this is done via a function
probABC = zeros(matrix_size);
for nn=1:count
A_i1 = find(strcmp(A_states, combinations{1,nn}(1,1)));
C_i1 = find(strcmp(C_states, combinations{1,nn}(3,1)));
if A_i1==1 %Heads
probB = probB_heads;
B_i1 = find(strcmp(B_states_heads, combinations{1,nn}(2,1)));
elseif A_i1==2 %Tails
probB = probB_tails;
B_i1 = find(strcmp(B_states_tails, combinations{1,nn}(2,1)));
end
for mm=1:count
A_i2 = find(strcmp(A_states, combinations{1,mm}(1,1)));
C_i2 = find(strcmp(C_states, combinations{1,mm}(3,1)));
if A_i2==1 %Heads
probB = probB_heads;
B_i2 = find(strcmp(B_states_heads, combinations{1,mm}(2,1)));
elseif A_i2==2 %Tails
probB = probB_tails;
B_i2 = find(strcmp(B_states_tails, combinations{1,mm}(2,1)));
end
if probA(A_i1,A_i2)~=0 || probB(B_i1,B_i2)~=0 || probC(C_i1,C_i2)~=0
if A_i1==A_i2
probABC(nn,mm) = probA(A_i1,A_i2)*probB(B_i1,B_i2)*probC(C_i1,C_i2);
elseif A_i1==1 && A_i2==2
probABC(nn,mm) = probA(A_i1,A_i2)*limit_dist_tails(1,B_i2)*probC(C_i1,C_i2);
elseif A_i1==2 && A_i2==1
probABC(nn,mm) = probA(A_i1,A_i2)*limit_dist_heads(1,B_i2)*probC(C_i1,C_i2);
end
end
end
end
%double check that the sum of the rows of probABC equal 1.
sum(probABC,2)

Sign in to comment.

Categories

Asked:

on 13 Jan 2016

Commented:

on 22 Jan 2016

Community Treasure Hunt

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

Start Hunting!