使用 MATLAB 比较列

发布于 2024-09-15 07:21:51 字数 71 浏览 2 评论 0原文

如何将矩阵的一列与前面的每一列进行比较?有没有一种方法可以在没有几个 for 循环的情况下做到这一点?

How do you compare a column of a matrix with each previous column? Is there a way to do it without a couple of for loops?

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

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

发布评论

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

评论(3

在巴黎塔顶看东京樱花 2024-09-22 07:21:51

对于矩阵 M,下面的代码将为您提供一个由零(假)和一(真)组成的逻辑行向量,用于判断给定列和前一列之间的所有元素是否相等(忽略第一列,因为没有前一列):

columnsAreEqual = all(diff(M,1,2) == 0);

这对于包含整数值的矩阵 M 来说效果很好。但是,如果您正在处理浮点值,则使用 由于浮点数的表示方式,计算列元素之间差异的 DIFF 函数可能会导致非常非零值。由于即使非常小的值仍然不等于零,因此您需要为差值选择一些容差值,低于该值您将认为两个数字实际上相等:

tolerance = 1e-6;  %# Any differences smaller than this are considered 0
columnsAreEqual = all(abs(diff(M,1,2)) < tolerance);

For a matrix M, the code below will give you a logical row vector of zeroes (false) and ones (true) for whether all the elements are equal between a given column and the previous column (ignoring the first column since there is no previous column):

columnsAreEqual = all(diff(M,1,2) == 0);

This will work fine for a matrix M that contains integer values. However, if you're dealing with floating point values then using the DIFF function to compute the differences between column elements may result in very small non-zero values due to how floating point numbers are represented. Since even a very small value is still not equal to zero, you will want to choose some tolerance value for the difference below which you would consider two numbers to be effectively equal:

tolerance = 1e-6;  %# Any differences smaller than this are considered 0
columnsAreEqual = all(abs(diff(M,1,2)) < tolerance);
世俗缘 2024-09-22 07:21:51

您想将每个项目与其左侧的项目进行比较吗?

X=yourMatrix
emptycolumn = zeros(size(X,1),1)
comparison = [X emptycolumn]==[emptycolumn X]

显然第一列和最后一列都是假的,没有任何意义,所以丢弃它们。

或者,如果您想比较整列是否相同,并获得行结果,只需使用 all(comparison,1)

Do you want to compare every item with the item on its left?

X=yourMatrix
emptycolumn = zeros(size(X,1),1)
comparison = [X emptycolumn]==[emptycolumn X]

Obviously the first and last columns are all false and don't mean anything so discard them.

Or if you want to compare whether the whole column is the same, and get a single row of results, just use all(comparison,1)

傲影 2024-09-22 07:21:51

是的

elementsAreEqualToElementToTheLeft = array(:,2:end) == array(:,1:end-1);
columnsAreEqualToColumsToTheLeft = all(elementsAreEqualToElementsToTheLeft,1);

Yes

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