how to use if loop to determine to make a plot

조회 수: 1 (최근 30일)
carly
carly 2022년 12월 5일
댓글: Jan 2022년 12월 6일
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에서 Audio I/O and Waveform Generation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by