How can the script decide when to send a variable as a function input or not?

1 view (last 30 days)
This is a question about MATLAB function inputs.
In my case, I am using a function to process a grayscale image. The function manipulates the pixel values in a number of ways. Additionally, I want the function to apply a mask to the image sometimes and sometimes not. To control this, I can apply a true/false flag as one of the function inputs. When a mask is required, I include the mask as an input to the function.
My question is: When I don't want to apply a mask, how do I deal with the mask input? In this case, I don't need to pass a mask to the function and I don't want to make a 'dummy' mask as this is not an elegant solution.
I'm probably missing something fundamental so please feel free to school me. Thanks.
Here's an example script (untested!) to help describe the situation:
% This line calls the function
myNewImage = image_processing_function (0, 'myImage.tif', myMask) % What to put for myMask when no mask required?
% Here is the function
function processedImage = image_processing_function (maskFlag, filename, mask_BW)
image = double(imread (filename));
if maskFlag==1 % check mask flag: 1->apply mask, 0->don't apply mask
image(~mask_BW) = NaN; % applt the mask
% do other stuff
processedImage = unit16(image);

Accepted Answer

Walter Roberson
Walter Roberson on 21 May 2022
No mask flag is needed
function processedImage = image_processing_function (filename, mask_BW)
image = double(imread (filename));
if nargin > 1
image(~mask_BW) = NaN; % apply the mask
Invoke the function with either just a file name, or with a file name and a mask.
  1 Comment
Steve Francis
Steve Francis on 21 May 2022
Thank you, Walter. I assumed incorrectly that it would throw up an error if I tried to call a function with a number of variables that were fewer than the input arguments defined in the function. I guess that your solution highlights that the order in which the arguments are listed in the function is important too.

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!

Translated by