0

I have a three dimensional matrix named Spr of size 5x5x500. The last dimension represents individuals while the first two dimensions refer to states. Hence, for each individual, I am storing a 5x5 matrix of transition probabilities from state i to state j. For instance, the last individual's transition probabilities are:

Spr( : , : , 500)

ans =

0.1386    0.3768    0.2286    0.1871    0.0688
0.1456    0.3959    0.2401    0.1966    0.0218
0.1475    0.4011    0.2433    0.1992    0.0090
0.1486    0.4039    0.2450    0.2006    0.0020
     0    1.0000         0         0         0

I would like to access the three dimensional matrix Spr with the first index being provided by a 500x1 matrix S which stores in which state the specific individual is currently in. Hence, my final result would be a 1x5x500 matrix. For instance, if the 500th individual is currently in state S(i)=2 the corresponding row for this individual would correspond to:

Spr(S(i),:,i)

0.1456    0.3959    0.2401    0.1966    0.0218 

How can I do that without using loops?

I've tried using the sub2ind function in Matlab but it doesn't work as it requires all the indexes be integers and essentially my second index is the character ":" .

1 Answer 1

1

Just to fullfill the "no loops" requirement:

N=sum(bsxfun(@times,permute(full(sparse(S,1:numel(S),1)),[1,3,2]),Spr),1)

The trick is to build up a indexing matrix which selects the right content using times. This solution is okay, but I don't like it because it's slower and less memory efficient than this much simpler solution using a for loop:

N=nan(1,size(Spr,2),size(Spr,3))
for k=1:size(Spr,1)
    N(1,:,S==k)=Spr(k,:,S==k)
end
Sign up to request clarification or add additional context in comments.

1 Comment

Indeed the for loop seems much simpler. I need to embed this operation within another for loop and I was afraid that it would be very time consuming having nested loops. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.