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

3 visualizaciones (últimos 30 días)
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
end
% do other stuff
processedImage = unit16(image);
end

Respuesta aceptada

Walter Roberson
Walter Roberson el 21 de Mayo de 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 comentario
Steve Francis
Steve Francis el 21 de Mayo de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Interactive Control and Callbacks en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by