Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to (fastly) convert matrices with values that are <= a threshold to binary matrices.

enter image description here

I used a call to Binarize, but I don't like the Image and ImageData conversions as they obfuscate the code. This code is also meant to be didactical and I obtain the matrices from real images in the real use case.

I couldn't write a faster thing using conditionals.

Suggestions?

share|improve this question
2  
Boole[Map[#<=95&,mat,{2}]]? – IPoiler Jan 22 at 1:31
2  
Please post correctly formatted, copy-and-pastable Mathematica code instead of screenshots (at 581 rep, you must have heard this by now, right?). – march Jan 22 at 3:20
up vote 2 down vote accepted
mat = {{209, 64, 112}, {8, 96, 253}, {65, 200, 95}};
Unitize[mat, 95];

This is fast, but not faster than your version:

mat = RandomInteger[{1, 300}, {1000, 1000}];
Unitize[mat, 95]; // AbsoluteTiming // First
ImageData[Binarize[Image[mat], 94]]; // AbsoluteTiming // First
UnitStep[mat - 95]; // AbsoluteTiming // First
Boole[Map[# <= 95 &, mat, {2}]]; // AbsoluteTiming // First
Sign[mat - 95] /. {-1 -> 0}; // AbsoluteTiming // First

enter image description here

and

mat = RandomInteger[{1, 300}, {10000, 10000}];
Unitize[mat, 95]; // AbsoluteTiming // First
ImageData[Binarize[Image[mat], 94]]; // AbsoluteTiming // First
UnitStep[mat - 95]; // AbsoluteTiming // First

enter image description here

share|improve this answer
    
The only potential issue with Unitize is numbers less than -t will be 1, not 0. But if OP's matrices have nonnegative elements, it's not a problem. – Chip Hurst Jan 22 at 16:16
    
@ChipHurst. Yeah, I actually always forget about that behavior of Unitize. I imagine in this case it's good, since he obtains the data from images. – march Jan 22 at 16:48

I think this does what you're asking for.

t = 95;
M = {{209, 64, 112}, {8, 96, 253}, {65, 200, 95}};

UnitStep[M - t]
{{1, 0, 1}, {0, 1, 1}, {0, 1, 1}}
share|improve this answer

You can also use the Sign function, though you have to replace the -1 with 0

Sign[m - t] /. {-1 -> 0}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.