简体   繁体   English

Matlab:用矩阵索引多维数组

[英]Matlab: Indexing multidimensional array with a matrix

I have a three dimensional matrix named Spr of size 5x5x500 . 我有一个名为Spr的三维矩阵,大小为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. 因此,对于每个人,我将存储从状态i到状态j的5x5转移概率矩阵。 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. 我想访问三维矩阵Spr,其中第一个索引由500x1矩阵S提供,该矩阵存储特定个体当前处于哪个状态。因此,我的最终结果将是1x5x500矩阵。 For instance, if the 500th individual is currently in state S(i)=2 the corresponding row for this individual would correspond to: 例如,如果第500个人当前处于状态S(i)= 2,则该个人的相应行将对应于:

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 ":" . 我已经尝试过在Matlab中使用sub2ind函数,但是它不起作用,因为它要求所有索引都是整数,并且基本上我的第二个索引是字符“:”

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 . 诀窍是建立一个索引矩阵,该矩阵使用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: 这个解决方案是可以的,但是我不喜欢它,因为它比使用for循环的简单得多的解决方案更慢,内存效率更低:

N=nan(1,size(Spr,2),size(Spr,3))
for k=1:size(Spr,1)
    N(1,:,S==k)=Spr(k,:,S==k)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM