Reputation: 2299
I have a matrix A
in Matlab of dimension mxn
. I want to construct a vector B of dimension mx1
such that B(i)=1
if all elements of A(i,:)
are equal and 0
otherwise. Any suggestion? E.g.
A=[1 2 3; 9 9 9; 2 2 2; 1 1 4]
B=[0;1;1;0]
Upvotes: 1
Views: 166
Reputation: 112769
Some more alternatives:
B = var(A,[],2)==0;
B = max(A,[],2)==min(A,[],2)
Upvotes: 2
Reputation: 104555
Here's another example that's a bit more obfuscated, but also does the job:
B = sum(histc(A,unique(A),2) ~= 0, 2) == 1;
So how does this work? histc
counts the frequency or occurrence of numbers in a dataset. What's cool about histc
is that we can compute the frequency along a dimension independently, so what we can do is calculate the frequency of values along each row of the matrix A
separately. The first parameter to histc
is the matrix you want to compute the frequency of values of. The second parameter denotes the edges, or which values you are looking at in your matrix that you want to compute the frequencies of. We can specify all possible values by using unique
on the entire matrix. The next parameter is the dimension we want to operate on, and I want to work along all of the columns so 2
is specified.
The result from histc
will give us a M x N
matrix where M
is the total number of rows in our matrix A
and N
is the total number of unique values in A
. Next, if a row contains all equal values, there should be only one value in this row where all of the values were binned at this location where the rest of the values are zero. As such, we determine which values in this matrix are non-zero and store this into a result matrix, then sum
along the columns of the result matrix and see if each row has a sum of 1. If it does, then this row of A
qualifies as having all of the same values.
Certainly not as efficient as Divakar's diff
and bsxfun
method, but an alternative since he took the two methods I would have used :P
Upvotes: 2