选择带有逻辑数组的3D矩阵的特定页面。

huangapple go评论59阅读模式
英文:

Select specific pages of 3D matrix with logic array

问题

我有一个3D矩阵,大小为n x m x p,其中p代表了1400个每日的2D数据数组。我还有一个逻辑数组,长度为p x 1。

我该如何创建一个新的3D矩阵,其中仅包含当p=1时的“页面”?

英文:

I have a 3D matrix n x m x p where p represents 1400 daily 2D data arrays. I also have a logical array the length of p x 1.

How do I create a new 3D matrix that contain only the 'pages' where p=1?

答案1

得分: 2

这应该与对于一维或二维数组的逻辑索引操作方式相同。

n = 3; m = 4; p = 5;
tmp = rand([n,m,p]);
p_mask = logical([1 0 1 0 0]);
new = tmp(:,:,p_mask);

一个小注意事项是,“logical”数组必须是“logical”类型。如果您使用一个包含1和0的双精度数组,Matlab会认为您想进行常规(位置)索引,并且会因为尝试访问索引为0的元素而报错,因为它超出了边界:

索引位置3无效。数组索引必须是正整数或逻辑值。

编辑:上面的类型转换为“logical”类型仅用于说明关于“logical”索引仅适用于逻辑类型,而不适用于浮点或整数类型的观点,并不是必需的。通常,逻辑索引的定义将基于某些条件,例如 p_mask = p_vals == 1;,其中 p_vals 将是包含1和0的数组。当然,也没有必要为逻辑掩码创建一个新变量 - new = tmp(:,:,p_vals == 1) 也可以正常工作。

英文:

This should work in the same way as logical indexing for 1D or 2D arrays.

n = 3; m = 4; p = 5;
tmp = rand([n,m,p]);
p_mask = logical([1 0 1 0 0]);
new = tmp(:,:,p_mask);

A small caveat is, that the "logical" array has to be of the logical type.
If you use a double array with ones and zeros, Matlab will assume that you want to do regular (positional) indexing and complain because you're trying to access the element at the index 0 which is out-of-bounds:

Index in position 3 is invalid. Array indices must be positive integers or logical values.

Edit: The cast to the logical type above just serves to illustrate the point about "logical" indexing only working with the logical type, and not with floating point or integer types. Usually, the logical indices would instead be defined by some condition like for example p_mask = p_vals == 1; where p_vals would be the array containing ones and zeros. It's of course also not necessary to create a new variable for the logical mask - new = tmp(:,:,p_vals == 1) would also do just fine.

答案2

得分: -3

在MATLAB中,从这个n*m*p矩阵中提取页面或切片就像选择要提取哪些页面一样简单。

np=1400
n=3;m=3;                   % 页面大小,仅作示例

A=randi([-20 20],n,m,np);  % 输入矩阵 n x m x p

p=randi([0 1],1,np);       % 选择器

p_selection=find(p==1);

B=A(:,:,p_selection);      % 选择的页面
英文:

In MATLAB pulling pages or slices off this n*m*p matrix is as simple as choosing what pages to take.

np=1400
n=3;m=3;                   % page size, just as example

A=randi([-20 20],n,m,np);  % the n x m x p input matrix

p=randi([0 1],1,np);       % selector

p_selection=find(p==1);

B=A(:,:,p_selection);      % selected pages

huangapple
  • 本文由 发表于 2023年6月9日 03:22:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76435095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定