Replace non-zero with inf one-liner matlab

Alec Jacobson

December 19, 2022

weblog/

One of the worst design aspects of matlibberish is how anonymous functions are handled. Anonymous functions are the only way to define functions in the workspace without files. Script files can have functions at the bottom but after evaluating the script they're not accessible from the workspace. So I often end up hacking around this by chaining small anonymous functions. Since anonymous functions in matlab can't have multiple lines (and thus no assignment or auxiliary variables), it can be awkward to do replacements. Here's a funny one to replace non-zeros in an (dense) array with infs by abusing divide by zero.

nonzero_to_inf = @(B) ~~B./~B;