How to write a function where the input arguments depend on the values within a window from nlfilter

I'm trying to write a script that performs a function on each cell in an array (elevation data, for context).
I need to find a value for each cell depending on those in its neighborhood (neighborhood size unimportant just now)
I'm using nlfilter to do this. The function involves several steps, and the inputs for the function will depend on the values within each neighborhood, so:
output = nlfilter(input,neighborhood_size,function);
function a = fun_name(neighborhood)
neighborhood_mean = mean2(neighborhood);
...etc
'function' needs to find the mean of each neighborhood, then subtract this mean from each cell in the neighborhood, and find the mean value of cells where mean>0.
There are several further steps but they depend on me being able to complete the above.
How do I specify that the input arguments for the function are whatever is in the neighborhood at the time?

 Accepted Answer

How do I specify that the input arguments for the function are whatever is in the neighborhood at the time?
That is what nlfilter already automatically assumes. So if I understood your post, your code should really look something like the following:
output = nlfilter(double(input),neighborhood_size,@fun_name);
function a = fun_name(neighborhood)
neighborhood_mean = mean2(neighborhood);
subset = (neighborhood>neighborhood_mean);
a=mean(neighborhood(subset));
end

1 Comment

Thanks Matt!
After I posted I spent a good while staring at the documentation and thought what you said might be the case, very useful to have the clarification.
Thanks again.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!