MATLAB Answers

Using cellfun and regexp question

15 views (last 30 days)
m j
m j on 30 Jul 2020
Commented: the cyclist on 31 Jul 2020
I have a cell called storedSamplerates = 1X9;
Each cell has a string ex:
storedSamplerates{1} = 'SAMPLERATE: 50000'
storedSamplerates{2} = 'samplerate:200000'
I am trying to remove the 'SAMPLERATE:' and 'samplerate:' portion of the cells regardless of case, so only the number is left. I can successfully use regexp with 'ignorecase', to remove this in a loop with:
sampleRates = regexp(storedSamplerates{i},'(\d+)','match','ignorecase');
So that im only left with numbers.
sampleRates{1} = '50000';
sampleRates{2} = '200000'
But I wanted to try using cellfun to have simpler code and have failed:
sampleRates(cellfun(@(x) regexp(x ,'(\d+)','match','ignorecase'),storedSamplerates));
Using cellfun and regexp seems possible,I just dont know where im messing up?

  1 Comment

Stephen Cobeldick
Stephen Cobeldick on 31 Jul 2020
Note that because your regular expression does not match any alphabetic characters (it only matches digits) the 'ignorecase' option is completely superfluous. It does nothing, zilch, nada, zero. Get rid of it.
Also the grouping parentheses do nothing. Get rid of them.

Sign in to comment.

Accepted Answer

the cyclist
the cyclist on 31 Jul 2020
Edited: the cyclist on 31 Jul 2020
I think this does what you want.
storedSamplerates{1} = 'SAMPLERATE: 50000';
storedSamplerates{2} = 'samplerate:200000';


m j
m j on 31 Jul 2020
Thanks,this does exactly what I wanted!
Stephen Cobeldick
Stephen Cobeldick on 31 Jul 2020
@m j: you picked the slower, more complex solution (1e4 iterations):
Elapsed time is 2.519055 seconds. % this complex answer
Elapsed time is 0.127693 seconds. % my simple answer

Sign in to comment.

More Answers (1)

Stephen Cobeldick
Stephen Cobeldick on 31 Jul 2020
Edited: Stephen Cobeldick on 31 Jul 2020
The simple and efficient solution is to use the 'once' option:
sampleRates = regexp(storedSamplerates,'\d+','match','once');
% ^^^^^^^^^^^^^^^^^ entire array, no indexing!
Wrapping regexp in cellfun does much the same thing, just slower and more complex.


Walter Roberson
Walter Roberson on 31 Jul 2020
This is what I would use.
the cyclist
the cyclist on 31 Jul 2020
Yes, should definitely swap to this accepting this one! The cellfun is a needless complication in my solution.

Sign in to comment.


Community Treasure Hunt

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

Start Hunting!

Translated by