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

1 次查看(过去 30 天)
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

采纳的回答

Walter Roberson
Walter Roberson 2022-5-21
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 个评论
Steve Francis
Steve Francis 2022-5-21
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Author Block Masks 的更多信息

标签

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by