Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test varargin for existence string pattern

I have a function that takes varargin with a flexible number of inputs of different types. I want to check the variable for the existence of a certain string/substring e.g.

regexpi(varargin,'test');

this works for varargin={'a','b'} however it fails if there are other datatypes. How can I easily (fewest codelines) get a logical matrix that tests for the existence of test? here's something annoyingliy convoluted I came up with:

varargin={'a',1,'test',{2}};
logi=num2cell(zeros(size(varargin))); %logical vector 'is string present or not';
logi(cellfun(@isstr,varargin))=regexp(varargin(cellfun(@isstr,varargin)),'test'); 
%outputs a cell array where numbers > 0 represent 'string found'
like image 387
user2305193 Avatar asked Sep 19 '26 18:09

user2305193


2 Answers

You could use isequal for a quick fix

bTest = cellfun( @(x) isequal( x, 'test' ), varargin );

A more verbose solution might be to use the inputParser and standard "name-value pair" syntax which is present in a lot of MATLAB functions.

function myFunc( varargin )
    % 'option' is the name of this optional parameter
    % varargin = {'option', 'test'}; 

    p = inputParser();
    p.addOptional( 'option', '' ); % Optional parameter, default to empty
    p.parse( varargin{:} );
    p.Results.option % = 'test' for the example varargin
like image 139
Wolfie Avatar answered Sep 21 '26 08:09

Wolfie


I would use this, which is similar to your code but simpler:

varargin = {'abcd', 'efg', [1 2 3 4], {10; 20}};
pattern = 'bc';
result = cellfun(@(x) ischar(x) && ~isempty(regexpi(x, pattern)), varargin);

Note how the use of && in the anonymous function prevents the test to be applied to non-char arguments.

like image 44
Luis Mendo Avatar answered Sep 21 '26 07:09

Luis Mendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!