input
x = [2 NaN 3 5 NaN; 1 NaN 4 9 NaN; 8 -2 7 6 -2; 7 4 8 5 4];
output
y_correct = [2 NaN 3 5; 1 NaN 4 9; 8 -2 7 6; 7 4 8 5];
First test case is invalid. Please fix it.
I have fixed it. Also rescored your score. Your solution is now correct.
A more complete description of what we're supposed to achieve would be useful. What are we supposed to do if a row has less elements than the others after applying unique? Pad it with zero as your second test seem to imply?
The objective of the problem is to find unique columns in the matrix, performing like unique(A,'columns','stable'), but treating NaN as equal numbers.
The explanation of Peng is correct. I inspired from the function of "isequalwithequalnans". You cannot use to test the equality of two arrays which contain nan values with the function of "isequal". The purpose is to write a function something like "uniquewithequalnans"
As standard unique does not operate on columns I didn't even realise that the example had two identical columns. I saw the problem as just remove the unique elements in each row which could potentially result in rows of different length. Hence my initial question.
??? You're not allowed to have more than one NaN, but you can have as many 0's or 1's as you like? What, exactly, do you mean by 'unique'?
An easy way to defeat that solution would be to use proper floating point numbers in the test suite. x = pi is enough to make it fail.
Yes, indeed. I have added test cases and rescored all solutions. Some of them failed.
Don't you think this is just a matter of the common round-off error for floating point numbers? Indeed, people rarely use exact equality == for floating-point numbers, which is probably why MATHWORKS has introduced uniquetol, as opposed to unique, to determine unique floating point numbers WITHIN TOLERANCE. If you insist exact equality must be used here, there are many workarounds anyway... My new solution is one of the examples.
No, this has nothing to do with round-off error. The solution itself rounds massively the input. If I pass x = pi to unique, I expect pi as an output, not 3.1416.
I should have been more careful with my wording. I meant that the issue you pointed out is due to "rounding" of num2str. num2str(pi) rounds pi to 3.1416. To remedy this, you can increase the default precision of num2str using its 2nd input parameter. For instance, num2str(x,20) should work for all floating point numbers including pi. This can be checked as follows: >> x = [pi,rand(1,10),Inf,NaN,sqrt(2)]; >> isequaln(str2num(num2str(x,20)),x)
402 Solvers
Number of 1s in the Binary Representation of a Number
313 Solvers
68 Solvers
149 Solvers
Matlab Basics - Create a row vector
198 Solvers