如何在 MATLAB 中使用数组掩码缩小矩阵?
这似乎是我的一个非常常见的问题:
data = [1 2 3; 4 5 6];
mask = [true false true];
mask = repmat(mask, 2, 1);
data(mask) ==> [1; 4; 3; 6]
我想要的是 [1 3; 4 6]
。
是的,我可以将其重塑
到正确的大小,但这似乎是错误的方法。有更好的办法吗?当数据实际上是矩形时,为什么data(mask)
不返回矩阵?我知道在一般情况下可能不是,但在我的情况下,因为我的原始掩码是一个数组,所以它总是会是。
推论
感谢您的回答,我也想指出这也适用于返回数字索引的任何内容,例如 ismember
、sort
或独特
。
当您可以使用此概念一次完成时,我曾经从 sort
获取第二个返回值并将其手动应用于每一列。
This seems to be a very common problem of mine:
data = [1 2 3; 4 5 6];
mask = [true false true];
mask = repmat(mask, 2, 1);
data(mask) ==> [1; 4; 3; 6]
What I wanted was [1 3; 4 6]
.
Yes I can just reshape
it to the right size, but that seems the wrong way to do it. Is there a better way? Why doesn't data(mask)
return a matrix when it is actually rectangular? I understand in the general case it may not be, but in my case since my original mask is an array it always will be.
Corollary
Thanks for the answer, I just also wanted to point out this also works with anything that returns a numeric index like ismember
, sort
, or unique
.
I used to take the second return value from sort
and apply it to every column manually when you can use this notion to do it one shot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这将为您提供您想要的:
这是可行的,因为您可以简单地将逻辑索引
mask
应用于列,并使用:
选择所有行。即使使用二维逻辑数组作为输入,输出也将是索引值的列数组。这是因为不能保证索引元素可以组织成二维(即矩形)输出。考虑一下您的 2-D 掩码是否如下:
这将索引 3 个值,这些值除了输出的行或列向量之外无法组织成任何内容。这是另一个示例:
这将索引 4 个值,但 3 个值来自第一行,1 个值来自第二行。这些值应该如何形成矩形输出矩阵?由于通常对于任意二维索引矩阵没有明确的方法来执行此操作,因此返回索引值的列向量。
This will give you what you want:
This works because you can simply apply the logical index
mask
to the columns, selecting all the rows with:
.Even when a 2-D logical array is used for an input, the output will be a column array of indexed values. This is because there is no guarantee that the indexed elements can be organized into a 2-D (i.e. rectangular) output. Consider if your 2-D mask were the following:
This would index 3 values, which can't be organized into anything but a row or column vector for the output. Here's another example:
This would index 4 values, but 3 are from the first row and 1 is from the second row. How should these values be shaped into a rectangular output matrix? Since there's no clear way to do this in general for an arbitrary 2-D index matrix, a column vector of indexed values is returned.