Checking the variable for specific string

조회 수: 17 (최근 30일)
Ravikumar Mevada
Ravikumar Mevada 2019년 7월 31일
편집: Adam Danz 2019년 7월 31일
Very new to Matlab. I need to give 'high' or 'low' in one function's input as shown below. How can I make sure that the variable only accept 'high' or 'low'? If anything else, then there will be an error like 'filter type error'.
Using code bellow, gives error even with 'high' and 'low' input.
Thanks!
function [Y] = butter2filtfilt(x, Fs, Fcutoff, Type)
if Type~= "high" || Type~= "low"
error ('Filter type error')
end
end
>> LF = butter2filtfilt(ecg, 257, 0.15, 'low');
Error using butter2filtfilt (line 6)
Filter type error
  댓글 수: 1
Steven Lord
Steven Lord 2019년 7월 31일
You've received a couple alternative solutions, but as an explanation for why this doesn't work that if statement is equivalent to "If type is not equal to 'high' or type is not equal to 'low', throw an error".
So what if type is equal to 'high'? The "type is not equal to 'high'" portion of that sentence is false, but the "type is not equal to 'low'" portion is true. Since the condition is false or true, the if is satisfied and so you throw an error.
The same holds if type is equal to 'low', just in reverse order. The first portion is true and the second portion is false.
You want to error if type is not equal to 'high' and type is not equal to 'low', not if one or the other is true.

댓글을 달려면 로그인하십시오.

채택된 답변

Alex Mcaulley
Alex Mcaulley 2019년 7월 31일
function [Y] = butter2filtfilt(x, Fs, Fcutoff, Type)
if ~ismember(Type,{'high','low'})
error ('Filter type error')
end
end
  댓글 수: 5
madhan ravi
madhan ravi 2019년 7월 31일
"How can I make sure that the variable only accept 'high' or 'low'? If anything else, then there will be an error like 'filter type error'. "
Adam Danz
Adam Danz 2019년 7월 31일
편집: Adam Danz 2019년 7월 31일
That doesn't mean the user wants to go against typical matlab syntax and force case sensitive input strings on what appears to be a binary flag.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Adam Danz
Adam Danz 2019년 7월 31일
편집: Adam Danz 2019년 7월 31일
This solution uses strcmpi() which which compares strings, allowing for case insensitivity so "High" or "LOW" won't cause an error. When there is an error, it provides the "Type" string that caused the error.
function [Y] = butter2filtfilt(x, Fs, Fcutoff, Type)
options = ["high", "low"];
if ~any(strcmpi(Type, options))
error('Filter type error. ''%s'' not recognized.', Type)
end
end

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by