how to use if loop to determine to make a plot

1 次查看(过去 30 天)
i cant post full code on here to keep my code private
if im making a function: function[output] = function(input1, input2, input3)
if input3 determines whether or not to make a plot, how can i go about it? in my code i cant directly ask the user to "input yes or no to make a plot" because i can only explain that yes mean to make one and no means not to make a plot in my syntax comments, so i dont think i can use strcmpi
this is what i have so far
if nargin == 3 && input3 == 'yes'
input3 = true;
else
input3 = false;
end
if nargin < 3 || isempty(input3)
input3 = true;
end

回答(1 个)

Jan
Jan 2022-12-5
编辑:Jan 2022-12-5
function output = myfcn(input1, input2, input3)
if nargin < 3
doPlot = true; % Default if 3rd input is not provided
else
doPlot = strcmpi(input3, 'yes');
end
if doPlot
plot()
end
end
Alternative:
if nargin < 3
input3 = 'yes'; % Default if 3rd input is not provided
end
doPlot = strcmpi(input3, 'yes');
The modern method is:
function out = myfcn(in1, in2, in3)
arguments
in1
in2
in3 char = 'yes' % Default value
end
doPlot = strcmpi(in3, 'yes');
if doPlot
plot(in1, in2, 'ro');
end
end
  2 个评论
carly
carly 2022-12-6
what if user inputs 'no'. wont it say "unrecognized function or variable 'no' "
Jan
Jan 2022-12-6
There is no try to access a variable or function called 'yes' or 'no'. So this error message will not appear. Simply try it by your own. You can run the code with different inputs.
If the 3rd input is 'no', strcmpi(in3, 'yes') replies false.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Filter Analysis 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by