Clear Filters
Clear Filters

return value of [ ] for an 'if' or 'for' function

19 views (last 30 days)
Say I have any function and the input can be input = 123.
For this function, only numbers can work as the input or else the return value should be [ ].
So if i were to have input = 'abc', the return value would need to show [ ].
How can I do this? If the input passes that first test it needs to be able to run the rest of the code.
Here is something i tried, it did not work.
Distance = 'abc'
if Distance = lettersPattern
res = []
end
Additionally, how can i also link the part abvoe to another requisite. If the input is empty to say 'unknown'?
if isempty(cLine)
res = 'unknown'
end

Accepted Answer

Akira Agata
Akira Agata on 23 Feb 2022
How about the following?
function output = yourFunction(input)
if isempty(input)
output = 'unknown';
elseif isa(input,'numeric')
output = input;
else
output = [];
end
end
  1 Comment
Akira Agata
Akira Agata on 23 Feb 2022
Well, in that case the Regular expression will work, like:
function output = yourFunction2(input)
str = regexp(input,'^\d{3}-\d{2}-\d{2}$','match');
if ~isempty(str)
output = input;
else
output = [];
end
end
For example:
>> yourFunction2('000-01-00')
ans =
'000-01-00'
>> yourFunction2('000-01-0a')
ans =
[]

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!