Using cellfun and regexp question

조회 수: 13 (최근 30일)
m j
m j 2020년 7월 30일
댓글: the cyclist 2020년 7월 31일
Hello,
I have a cell called storedSamplerates = 1X9;
Each cell has a string ex:
storedSamplerates{1} = 'SAMPLERATE: 50000'
storedSamplerates{2} = 'samplerate:200000'
etc.....
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'
etc....
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
Stephen23
Stephen23 2020년 7월 31일
편집: Stephen23 2020년 7월 31일
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.

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

채택된 답변

the cyclist
the cyclist 2020년 7월 31일
편집: the cyclist 2020년 7월 31일
I think this does what you want.
storedSamplerates{1} = 'SAMPLERATE: 50000';
storedSamplerates{2} = 'samplerate:200000';
cellfun(@(str)regexp(str,'\d*','match'),storedSamplerates)
  댓글 수: 2
m j
m j 2020년 7월 31일
Hey,
Thanks,this does exactly what I wanted!
Stephen23
Stephen23 2020년 7월 31일
편집: Stephen23 2020년 7월 31일
@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

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

추가 답변 (1개)

Stephen23
Stephen23 2020년 7월 31일
편집: Stephen23 2020년 7월 31일
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.
  댓글 수: 2
Walter Roberson
Walter Roberson 2020년 7월 31일
This is what I would use.
the cyclist
the cyclist 2020년 7월 31일
Yes, should definitely swap to this accepting this one! The cellfun is a needless complication in my solution.

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

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by