简体   繁体   English

使用matlab索引矩阵中的行

[英]indexing rows in matrix using matlab

Suppose I have an empty m-by-n-by-p dimensional cell called "cellPoints", and I also have a D-by-3 dimensional array called "cellIdx" where each row i contains the subscripts in "cellPoints". 假设我有一个空的m×n×p维单元,称为“ cellPoints”,我还有一个D×3维数组,称为“ cellIdx”,其中每行i都包含“ cellPoints”中的下标。 Now I want to compute "cellPoints" so that cellPoints{x, y, z} contains an array of row numbers in "cellIdx". 现在,我要计算“ cellPoints”,以便cellPoints {x,y,z}在“ cellIdx”中包含一个行号数组。

A naive implementation could be 天真的实现可能是

for i = 1:size(cellIdx, 1)
    cellPoints{cellIdx(i, 1), cellIdx(i, 2), cellIdx(i, 3)} = ...
    [cellPoints{cellIdx(i, 1), cellIdx(i, 2), cellIdx(i, 3)};i];
end

As an example, suppose 例如,假设

cellPoints = cell(10, 10, 10);% user defined, cannot change
cellIdx = [1, 3, 2;
           3, 2, 1;
           1, 3, 2;
           1, 4, 2]

Then 然后

cellPoints{1, 3, 2} = [1;3];
cellPoints{3, 2, 1} = [2];
cellPoints{1, 4, 2} = [4];

and other indices of cellPoints should be empty 而cellPoints的其他索引应为空

Since cellIdx is a large matrix and this is clearly inefficient, are there any other better implementations? 由于cellIdx是一个大矩阵,而且效率很低,因此还有其他更好的实现吗?

I've tried using unique(cellIdx, 'rows') to find unique rows in cellIdx, and then writing a for-loop to compute cellPoints, but it's even slower than above. 我尝试使用unique(cellIdx,'rows')在cellIdx中查找唯一的行,然后编写一个for循环来计算cellPoints,但它的速度甚至比上面要慢。

See if this is faster: 看看这是否更快:

cellPoints = cell(10,10,10); %// initiallize to proper size
[~, jj, kk] = unique(cellIdx, 'rows', 'stable')
sz = size(cellPoints);
sz = [1 sz(1:end-1)];
csz = cumprod(sz).'; %'// will be used to build linear index
ind = 1+(cellIdx(jj,:)-1)*csz; %// linear index to fill cellPoints
cellPoints(ind) = accumarray(kk, 1:numel(kk), [], @(x) {sort(x)});

Or remove sort from the last line if order within each cell is not important. 如果每个单元格中的顺序都不重要,则从最后一行删除sort

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

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