Given a matrix, find all elements that exist in every row.
For example, given
A = 1 2 3 5 9 2 5 9 3 2 5 9 1 2 1 5 5 1 3 2
the answer would be the vector '2 5'. Elements should be returned sorted ascending.
Note there is no guarantee that there are any such elements; if there are none, the routine should return the empty set. Also, the matrix might contain NaNs, repeats, or very large or very small elements.
Any version of "empty" should be acceptable as correct.
For example, intersect can output a 1x0 empty matrix. That should be allowed.
Somehow the assert is triggered if the function returns a [] that has been "sorted".
If I include that code
if ~isempty(y)
y = sort(unique(y));
end
no assert is triggered. Seem strange!
How can the leading solution be 0??
Following many comments, the Test Suite should be amended to check for an empty output vector using "isempty", rather testing for equality to []. Such an amendment is appropriate, and would not break any of the previously submitted successful solutions. —DIV
This is far from elegant, but works! Is there a a vectorised way to approach this in a much more efficient way?
function y = common_by_row(x)
y=[];
[r,c]=size(x);
if r>0
a=x(1,:);
cnt=zeros(1,c);
for j=1:c
for i=1:r
if isempty(find(x(i,:)==x(1,j)))==0
cnt(j)=cnt(j)+1;
end
end
end
for j=1:c
if cnt(j)==r&&x(1,j)~=NaN&&ismember(x(1,j),y)==0
y=[y x(1,j)];
end
end
y=sort(y);
end
end
Why doesn't this work?? :( it returns an empty array as I specified...
Why is this incorrect? It's failing when the output is = [];
In matlab, I'm getting output as:
y =
1×0 empty double row vector
Is that not the same thing?
My code is correct but it is showing not a solution.......help me
The fact that an empty 0-by-1 matrix does not equal [] is a bit offputting.
I had to add an extra if-clause because the assertion isn't particularly forgiving about its definition of an "empty matrix".
The test suite should consider a 0x0 empty matrix (as given by y = []) as equivalent to a 1x0 empty matrix (which results from the code above it
solution uses recursion
nice !!!
argh! trying to debug third test case. I am returning a []. assert is comparing that to a []. How do I fail?
Both 3rd test case and 5th evaluate to [] locally, but I fail the cody asserts.
As others have later commented, the assert requires a 0×0 size 'empty' vector. See edited version in Solution 1276044.