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)
Test | Status | Code Input and Output |
---|---|---|
1 | Pass |
%%
x = [2 NaN 3 5 NaN;
1 NaN 4 9 NaN;
8 -2 7 6 -2;
7 4 8 5 4];;
y_correct = [2 NaN 3 5;
1 NaN 4 9;
8 -2 7 6;
7 4 8 5];
assert(isequalwithequalnans(unique_with_nan(x),y_correct))
|
2 | Pass |
%%
x = [1 0 0 1;NaN 1 0 NaN;NaN 0 1 NaN;0 0 0 0];
y_correct = [1 0 0;NaN 1 0;NaN 0 1;0 0 0];
assert(isequalwithequalnans(unique_with_nan(x),y_correct))
|
3 | Pass |
%%
x = [1 0 1 1 1 1 0;0 1 1 1 1 1 0;0 0 NaN NaN NaN NaN 0;0 0 NaN NaN NaN NaN 0;0 0 NaN NaN NaN NaN 0;0 0 0 0 0 0 0;0 0 0 0 0 0 1];
y_correct = [1 0 1 0;0 1 1 0;0 0 NaN 0;0 0 NaN 0;0 0 NaN 0;0 0 0 0;0 0 0 1];
assert(isequalwithequalnans(unique_with_nan(x),y_correct))
|
4 | Fail |
%%
x = [2 NaN 3 5 NaN;
1 NaN 4 9 NaN;
8 pi 7 6 pi;
7 eps 8 5 eps];
y_correct = [2 NaN 3 5;
1 NaN 4 9;
8 pi 7 6;
7 eps 8 5];
assert(isequalwithequalnans(unique_with_nan(x),y_correct))
|
199 Solvers
351 Solvers
348 Solvers
Convert a vector into a number
503 Solvers
5115 Solvers
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!