I have the following function which calculates statistic parameters. I would like to pass this function to nlfilter
to do the calculation for a whole image. But the output of nlfilter
must be a scalar.
How can I convert this to a function handle suitable for use with nlfilter
so I can save the output of the function getStatistics2
?
The getStatistics2
function's output is an struct
array.
function [out] = getStatistics2(D)
D = double(D);
% out.MAX = max(D);%maximum
% out.MIN = min(D);%minimum
out.MEA = mean(D);%mean
out.MAD = mad(D);% mean absolute deviation y=mean(abs(X-mean(x)))
out.MED = median(D);%median
out.RAN = max(D) - min(D);%range
out.RMS = rms(D);%root mean square
out.STD = std(D);%stardard deviation
out.VAR= var(D);%variance
This is an interesting question. What's interesting is that your approach is almost perfect. The only reason it fails is because
struct
cannot be constructed using a numeric scalar input (i.e.struct(3)
). The reason I mention this is because somewhere during the execution ofnlfilter
(specifically inmkconstarray.m
), it calls the the following code:Where:
class
is'struct'
.value
is0
.size
is thesize()
of the input image, e.g.[100,100]
.... and this fails because
feval('struct', 0)
, which is equivalent tostruct(0)
- and this we already know to be invalid.So what do we do? Create a custom class that can be constructed this way!
Here's an example of one such class:
And here's how you can use it:
Notice that I have added an optional input (
outputAsStruct
) that can force the output to be astruct
array (and not an array of the type of our custom class, which is functionally identical to a read-onlystruct
).Notice also that by default
nlfilter
pads your array with zeros, which means that the(1,1)
output will operate on an array that looks like this (assumingWINDOW_SZ=3
):and not on
im(1:WINDOW_SZ,1:WINDOW_SZ)
which is:the "expected result" for
im(1:WINDOW_SZ,1:WINDOW_SZ)
will be found further "inside" the output array (in the case ofWINDOW_SZ=3
at index(2,2)
).