Ignoring nan in matrix.
Show older comments
Hello, I have a matrix which has a member like 5+0/0. I want this to come out as 5. Do you know how can I make this? I found different answers regarding changing nan to zero but i want to change nan to 5 as in previous example.
If my matrix came out as [5 4 3 2+0/0; 4 3 7 0/0+7] , I want to change this to [5 4 3 2; 4 3 7 7]
2 Comments
dpb
on 30 Jan 2021
>> [5 4 3 2+0/0; 4 3 7 0/0+7] ,
ans =
5 4 3 NaN
4 3 7 NaN
>>
There's no way to know what created the NaN at this point; you would have to have the components of the elements before the result is computed in order to be able to retrieve the portion of the calculation that is finite.
Would have to have the context in which these are being computed to see how to manage to do that -- if there is the result of some operation that does lead to the 0/0 expression, then breaking that out and containing in a try...catch...end block might be a way to provide a solution.
John D'Errico
on 30 Jan 2021
As dpb says, you cannot do this, not after the NaN was created. Well, I suppose you could, by overloading all of the basic operators in MATLAB, thus plus, minus, times, etc. Then you would need to internally trap for such an event, catching it to return the value you wish to see. Can you see a huge opportunity for bugs to arise? (I do.)
But even if you have the skill to write the code you want (if you did, you would not be asking this question), your code will now become INCREDIBLY slow. And all future code you will ever write will run like a horse with no legs.
Far better is to understand why a NaN gets created, and to formulate what you are doing so this does not happen.
Answers (0)
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!