[英]N-dimensional array indexing in Matlab : find array in middle
I am working with N-dimensional array and have a problem with the array indexing.我正在使用 N 维数组,但数组索引有问题。 I have a task to find an (N-1)-dimensional array in the middle N-dimensional array.
我有一个任务是在中间的 N 维数组中找到一个 (N-1) 维数组。
Let me explain in detail with 3D array.让我用 3D 数组详细解释。
A
is a 3-dimensional array that has split into groups. A
是一个 3 维数组,已拆分为多个组。 In each group, there are b
- number of 2-dimensional arrays in the group.在每个组中,有
b
- 组中二维数组的数量。 I have simulated it as:我将其模拟为:
b=5;
A=rand(2,2,20);
groups = reshape(A, size(A,1), size(A,2),b, []);
groups
is 4-dimensional array, the 4-th dimension is a number of groups ( here it 4). groups
是 4 维数组,第 4 维是组的数量(这里是 4)。
To find a middle in each group I have added the following loop:为了在每个组中找到一个中间人,我添加了以下循环:
for ii=1:size(groups,4) % Loop over all groups/slices
middle(:,:,ii) = groups(:,:,(w-1)/2+1,ii); % 1 2 3 4 5 : the middle is 3
end
middle
is 3-dimensional array that collects middle array in each group. middle
是一个 3 维数组,它收集每组中的中间数组。
As you see in my example I have used b=5
( odd number).正如您在我的示例中看到的,我使用了
b=5
(奇数)。 My problem is with even number b
.我的问题是偶数
b
。
I have tried to implement it as ( rewrite the loop above);我试图将它实现为(重写上面的循环);
l=rem(w,2);
for ii=1:size(groups,4) % Loop over all groups/slices
if l==1
middle(:,:,ii) = groups(:,:,(w-1)/2+1,ii);
else
middle(:,:,ii) = groups(:,:,(w-1)/2,ii);
end
end
But it doesn't work.但它不起作用。 Matlab gives me an error in the line
l=rem(w,2);
Matlab 在
l=rem(w,2);
行中给了我一个错误l=rem(w,2);
Could you suggest to me how I can fix it?你能告诉我如何修复它吗? Is there another way to implement it?
有没有另一种方法来实现它?
You should use floor
of ceil
to round the index to whichever element you want:您应该使用
floor
of ceil
将索引四舍五入到您想要的任何元素:
middle_index = floor((w-1)/2+1);
Here, the middle of 4 is 2, using ceil
you'd pick index 3.在这里,4 的中间是 2,使用
ceil
你会选择索引 3。
Next, you can extract the arrays in a single indexing operation:接下来,您可以在单个索引操作中提取数组:
middle = groups(:,:,middle_index,:);
Finally, use squeeze
or reshape
to get rid of the 3rd index:最后,使用
squeeze
或reshape
来摆脱第三个索引:
middle = squeeze(middle);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.