开发者

Changing '0's in a list to avoid divide by 0 errors

开发者 https://www.devze.com 2023-03-21 16:30 出处:网络
Suppose I have a nested list: {{2,0,3},{4,0,4},{0,0,9}}. I would like to change all the 0 to 0.00001, or some other small value, so that the final result is {{2,0.00001,3},{4,0.00001,4},{0.00001,0.000

Suppose I have a nested list: {{2,0,3},{4,0,4},{0,0,9}}. I would like to change all the 0 to 0.00001, or some other small value, so that the final result is {{2,0.00001,3},{4,0.00001,4},{0.00001,0.00001,9}}

How would I go about doi开发者_如何学JAVAng so without using the For and If functions?

Thanks in advance.


Maybe a better solution is to allow the division by zero, but suppress the warning:

In[1]:= Quiet[1/{{2, 0, 3}, {4, 0, 4}, {0, 0, 9}}, Power::infy]
Out[1]= {{1/2,ComplexInfinity,1/3}, {1/4,ComplexInfinity,1/4}, {ComplexInfinity,ComplexInfinity,1/9}}

But I guess if you want to replace the Integer 0 with 0.00001, then you could try

In[2]:= {{2, 0, 3}, {4, 0, 4}, {0, 0, 9}} /. 0 -> 0.00001
       1/%
Out[2]= {{2,0.00001,3},{4,0.00001,4},{0.00001,0.00001,9}}
Out[3]= {{1/2,100000.,1/3},{1/4,100000.,1/4},{100000.,100000.,1/9}}


{{2, 0, 3}, {4, 0, 4}, {0, 0, 9}} /. {0 -> 0.0001}
(*
-> {{2,0.0001,3},{4,0.0001,4},{0.0001,0.0001,9}}
*)

However, as @nomulous said, it's unlikely that this is the best way to achieve whatever it is you're after. So, what are you trying to do? What is the actual problem you are trying to solve?

EDIT: In your comment you mention that you're trying to divide images. Without seeing more code, I'd suggest something like this:

i1 = Image[ {{0, 1, 0}, {1, 0, 1}, {0, 1, 0}}]
i2 = Image[ RandomReal[1, {3, 3}]]
Image[Quiet[i2[[1]]/i1[[1]]] /. ComplexInfinity -> 1]

which extracts the list of data, divides, allowing division by zero to occur yielding ComplexInfinity, replaces ComplexInfinity by 1 (the maximum allowed) and then wraps Image around the resulting list.

Perhaps if you show more code it will be easier to suggest something better.

0

精彩评论

暂无评论...
验证码 换一张
取 消