You want to find all elements that exist in greater than 50% of the rows in the matrix.
For example, given
A = 1 2 3 5 9 2 5 9 3 2 5 8 1 2 1 5 5 1 3 2
the answer would be the row vector
[1 2 3 5]
since each of these appears three or more times in the rows of matrix A. 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 repeats, very large or very small numbers, or NaNs (though NaN should not be treated as a number to be returned in the output).
Tests aren't specifically adapted to this problem. The code for problem 67 (Find common elements in matrix works here).
Absolutely agree with Jean-Marie.
Tests is not good enough.
Not sure if the previous commenters have the same issue that I have, but I dislike that this test-suite makes a difference in how the empty-matrix is defined (See also comments for solution 167825).
I would suggest checking isempty' for the relevant solutions.
Ironically, simply including the example from the problem statement in the test suite would reject the current smallest ("best") solutions.
Indeed, the current leading solutions with size 29 yield only elements that exist in ALL of the rows in the matrix!
This needs another test case.
Many would fail this:
%%
x = [1 1 1 1;2 3 4 5;3 6 7 8];
y_correct = [3];
assert(isequal(common_by_row(x),y_correct))
function y = common_by_row(x)
tmp=[];
y=[];
z=[];
k=1;
[r,c]=size(x);
for i=1:r
for j=1:c
if x(i,j)~=NaN
if ismember(x(i,j),z)==0
z(k)=x(i,j);
k=k+1;
end
end
end
end
cnt=0;
for k=1:length(z)
for i=1:r
for j=1:c
if x(i,j)==z(k)
cnt=cnt+1;
end
end
end
tmp(k)=cnt;
cnt=0;
end
m=1;
for i=1:length(z)
if tmp(i)>0.5*r
y(m)=z(i);
m=m+1;
end
end
y=sort(y);
end
I know I have adapted code according to test cases. But was stuck in this one.
Don't know why an empty matrix 1-by-0 is not equal to the empty matrix [].
[] is 0-by-0. mtimes(ones(1,0), ones(0,1)) equals 0, mtimes([], ones(0,1)) is empty 0-by-1. This is one of the reasons.
I used exactly the same code as for problem 67.
Nice! But I think you made a mistake in if length(m)==size(x,1), according to the instruction, a number that appears more than half of total rows would be okay.
My solution fails on the magic, the wilkonson and the [1;2] inputs.
However, on my own computer each input works as expected.
Anyone has a hint on where I am going wrong?
Found it.
Due to the way the test-suite is set-up (using 'isequal'), MATLAB makes a difference between the values "[]" (size [0 0]) and "Empty matrix: 1-by-0" (size [1 0]), even though they are both considered empty.
268 Solvers
Celsius to Fahrenheit converter
327 Solvers
313 Solvers
07 - Common functions and indexing 1
308 Solvers
Create a two dimensional zero matrix
326 Solvers