MATLAB 仅从矩阵中删除某些零

发布于 2024-12-12 05:56:30 字数 188 浏览 0 评论 0原文

我已经看到很多关于如何删除前导和/或尾随零以及如何从向量或矩阵中删除所有零的答案。不过,我需要做的只是删除其中一些。我有两个矩阵,我只想删除它们都为零的条目。它们是二维 x 和 y 坐标,使用特征求解(如果需要,我可以提供更多详细信息),我只想删除两个矩阵在相同索引处包含零的值。我可以轻松地将矩阵转换为向量并使用向量,因此在任何一种情况下的任何帮助将不胜感激。

I have seen plenty of answers regarding how to remove leading and/or trailing zeros, and how to remove all zeros from a vector or matrix. What I need to do, though, is only remove some of them. I have two matrices, and I only want to remove the entries where both of them are zero. They are two-dimensional x and y coordinates, solved using characteristics (I can give more detail if needed) and I just want to remove the values where both matrices contain zeros at the same indices. I can easily convert the matrices into vectors and work with vectors, so any help in either case would be greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

爱的十字路口 2024-12-19 05:56:30

为了简单起见,我们假设您使用名为 XY 的向量(长度相同),并且您只想删除两个向量都为的条目零。方法如下(未测试):

% Find the indexes where either X or Y is different from zero
% (these are the indexes of the components we want to keep)
I = find(X~=0 | Y~=0);

% Select the desired components from X and Y
X=X(I);
Y=Y(I);

编辑:正如奥利在下面指出的那样(以及斯特凡诺进一步解释),您应该使用逻辑索引以获得更好的性能。

For the sake of simplicity, let's assume you're using vectors called X and Y (of the same length), and you want to remove only those entries where both vectors are zero. Here's how (not tested):

% Find the indexes where either X or Y is different from zero
% (these are the indexes of the components we want to keep)
I = find(X~=0 | Y~=0);

% Select the desired components from X and Y
X=X(I);
Y=Y(I);

Edit: As Oli has pointed out below (and stefano explained further), you should use logical indexing for better performance.

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