开发者

Comparing columns using MATLAB

How do you com开发者_高级运维pare a column of a matrix with each previous column? Is there a way to do it without a couple of for loops?


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);


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)


Yes

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜