如何在 MATLAB 中使用数组掩码缩小矩阵?

发布于 2024-08-30 09:43:23 字数 536 浏览 9 评论 0原文

这似乎是我的一个非常常见的问题:

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)不返回矩阵?我知道在一般情况下可能不是,但在我的情况下,因为我的原始掩码是一个数组,所以它总是会是。

推论

感谢您的回答,我也想指出这也适用于返回数字索引的任何内容,例如 ismembersort独特

当您可以使用此概念一次完成时,我曾经从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤星 2024-09-06 09:43:23

这将为您提供您想要的:

>> data = [1 2 3; 4 5 6];
>> mask = [true false true];
>> data(:,mask)

ans =

     1     3
     4     6

这是可行的,因为您可以简单地将逻辑索引 mask 应用于列,并使用 : 选择所有行。

即使使用二维逻辑数组作为输入,输出也将是索引值的列数组。这是因为不能保证索引元素可以组织成二维(即矩形)输出。考虑一下您的 2-D 掩码是否如下:

mask = [true false true; true false false];

这将索引 3 个值,这些值除了输出的行或列向量之外无法组织成任何内容。这是另一个示例:

mask = [true true true; true false false];

这将索引 4 个值,但 3 个值来自第一行,1 个值来自第二行。这些值应该如何形成矩形输出矩阵?由于通常对于任意二维索引矩阵没有明确的方法来执行此操作,因此返回索引值的列向量。

This will give you what you want:

>> data = [1 2 3; 4 5 6];
>> mask = [true false true];
>> data(:,mask)

ans =

     1     3
     4     6

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:

mask = [true false true; true false false];

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:

mask = [true true true; true false false];

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文