I have a simple problem that I'm looking for a fast implementation in Matlab. I have an array of values, let's say:
a = floor(rand(5,5).*255)
I then have a similarly sized threshold array, let's say it's:
a_thresh = floor(rand(5,5).*255)
For values within a
if they are 0.5x smaller than the corresponding value in a_thresh
I want the output to be 0 - similarly for 1.2x the value in a_thresh
should also be set to zero, i.e.:
a(a < a_thresh.*0.4) = 0
a(a > a_thresh.*1.2) = 0
For values between 0.4x and 0.5x and 1.0x and 1.2x I want a proportional amount and else where between 0.5 and 1.0 I want to use the value of a
unaltered. I thought I could use something like the following:
a(a>= a_thresh .* 0.4 && a <a_thresh.* 0.5) = ((a - a_thresh.*0.4)/(a_thresh.*0.5 a_thresh.*0.4)) .* a;
However, I get an error that says:
Operands to || and && operations must be convertible to logical scalar values
Any advice on how to solve this? Obviously I could use loops to do this and it would be trivial, but I want to keep the code vectorized.
in MATLAB, the || operator is the "short-circuit or" operator, and can only be used if the two sides compute scalars.
The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool . Logical OR has left-to-right associativity.
The short-circuit OR operator is || . When you use the element-wise & and | operators in the context of an if or while loop expression (and only in that context), they use short-circuiting to evaluate expressions. Otherwise, you must specify && or || to opt-in to short-circuiting behavior.
The thing about &&
is that it can operate only on scalars, whereas &
can operate on arrays as well. You should change the &&
to &
to make it work (you can read more about it in this question).
Update:
Regarding your second problem described in a comment: the number of elements on the left is different because you're using indices (selecting only certain elements), and on the right you're working with the entire matrix a
and a_thresh
.
You need to use indices in both sides, so I suggest storing it in a variable and then use it as an array subscript, along these lines:
idx = (a >= a_thresh*0.4 & a < a_thresh*0.5);
a(idx) = ((a(idx)-a_thresh(idx)*0.4) ./ (a_thresh(idx)*0.5*a_thresh(idx)*0.4)) .* a(idx);
I'm not sure if the calculation itself is correct, so I'll leave it to you to check.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With