[英]problems on index in matlab nd array
Here is a simplified example 这是一个简化的例子
x = reshape(1:2*4*3,2,4,3); % 3d array
i1 = [1 1 2]; % index in dim 1
i2 = [2 1 3]; % index in dim 2
I want to extract x(i1(ii),i2(ii),:)
, namely x(1,2,:); x(1,1,:); x(2,3,:)
我想提取
x(i1(ii),i2(ii),:)
,即x(1,2,:); x(1,1,:); x(2,3,:)
x(1,2,:); x(1,1,:); x(2,3,:)
x(1,2,:); x(1,1,:); x(2,3,:)
, which is of size [3,3]. x(1,2,:); x(1,1,:); x(2,3,:)
,大小为[3,3]。
But x(i1,i2,:)
gives a 3d array of size [3,3,3]. 但是
x(i1,i2,:)
给出了一个大小为[3,3,3]的3d数组。
So I used a stupid loop 所以我使用了一个愚蠢的循环
y = nan(length(i1),3);
for ii = 1 : 3
y(ii,:) = squeeze(x(i1(ii),i2(ii),:));
end
which gives 这使
3 11 19 1 9 17 6 14 22
I believe this must not be the fancy way. 我相信这绝不是一种奇特的方式。
You can reshape x
to a [8 * 3]
matrix and convert subscripts to linear indexes: 您可以将
x
重塑为[8 * 3]
矩阵并将下标转换为线性索引:
x = reshape(x,[],3);
y = x(sub2ind([2 4],i1,i2),:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.