使用 MATLAB 比较列
如何将矩阵的一列与前面的每一列进行比较?有没有一种方法可以在没有几个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于矩阵
M
,下面的代码将为您提供一个由零(假)和一(真)组成的逻辑行向量,用于判断给定列和前一列之间的所有元素是否相等(忽略第一列,因为没有前一列):这对于包含整数值的矩阵 M 来说效果很好。但是,如果您正在处理浮点值,则使用 由于浮点数的表示方式,计算列元素之间差异的 DIFF 函数可能会导致非常非零值。由于即使非常小的值仍然不等于零,因此您需要为差值选择一些容差值,低于该值您将认为两个数字实际上相等:
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):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:您想将每个项目与其左侧的项目进行比较吗?
显然第一列和最后一列都是假的,没有任何意义,所以丢弃它们。
或者,如果您想比较整列是否相同,并获得单行结果,只需使用
all(comparison,1)
Do you want to compare every item with the item on its left?
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)
是的
Yes