Here's a couple of suggestions:
First of all, you don't need to add 50 to each layer of the RGB matrix individually. You can just do:
b = b + 50;
Why do you reshape
b
before passing it tobsxfun
? The size of the output ofbsxfun
is the same as your image's, there's really no need in reshaping here anything.Regarding your
test
function, note what the official documentation ofbsxfun
states:A binary element-wise function of the form
C = fun(A,B)
accepts arraysA
andB
of arbitrary but equal size and returns output of the same size. Each element in the output arrayC
is the result of an operation on the corresponding elements ofA
andB
only.fun
must also support scalar expansion, such that ifA
orB
is a scalar,C
is the result of applying the scalar to every element in the other input array.So
bsxfun
performs singleton expansion and "inflates" its two input arrays to the same size, and then applies the specified function to the inflated arrays. The element-wise functionfun
operates, in fact, on the arrays, not scalars. I don't see any actual gain in employingbsxfun
here.That said, you can simplify your code as shown in Dan's suggestion, or implement it as a function:
function out = test(in, a); out = in; out(in > a) = a;
I assume that if you were using the value 210 instead of 200, you'd like to cap all gray levels with 210 as well, so you should really be using
a
instead of a hard-coded value 200. You could also write your function like so:function out = test(in, a) out = min(in, a);
and then invoke it with:
d = test(b, 200);
instead of the more complicated
d = bsxfun(@test, b, 200)
.Another alternative is to use
arrayfun
:d = arrayfun(@(x)test(x, 200), a);
or
d = arrayfun(@test, a, 200 * ones(size(a)));
in which
arrayfun
will applytest
element-wise, and thetest
function would need to operate only on scalars. However,arrayfun
usually runs slower than loops, let alone vectorized operations.For spatial analysis, check out
conv2
just like Dan suggested (or implement your own 2-D convolution, for the sake of practice). For Fourier analysis, consider using thefft2
andifft2
functions in the frequency domain.
Hope this helps!