how to use if loop to determine to make a plot

1 view (last 30 days)
carly
carly on 5 Dec 2022
Commented: Jan on 6 Dec 2022
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

Answers (1)

Jan
Jan on 5 Dec 2022
Edited: Jan on 5 Dec 2022
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 Comments
carly
carly on 6 Dec 2022
what if user inputs 'no'. wont it say "unrecognized function or variable 'no' "
Jan
Jan on 6 Dec 2022
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.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!