how to use strfind (or other method) to look in cell array to find strings NOT containing a certain pattern

조회 수: 65 (최근 30일)
Hello! I am trying to develop an automated plotting code for experimental results which scans through given folders and imports and plots the data in the files based on the name of the file. At the moment I import an array of cells for the filenames (each cell containing a single filename as characters) and a matrix with the associated data in it as doubles (number of columns = number of filename cells). I cycle through the filenames and only import/plot the data if the file name includes key strings like "IdsVbg", "PBS", "exo"...
For example:
if strfind(y{n}, 'PBS') & strfind(y{n}, 'flush')
p=plot(IdsVtgdata(2:end,n,2)/0.001,IdsVtgdata(2:end,n,1)/0.001,'color',cmapPBS(n,:));
end
Where y is the cell array of filenames and IdsVtgdata is the matrix of my data. This works fine, except instead of the above, I would like to plot something based on a filename that contains "PBS" but specifically NOT "flush". I tried
if strfind(y{n}, 'PBS') & not(strfind(y{n}, 'flush'))
and
if strfind(y{n}, 'PBS') & (strfind(y{n}, ~'flush'))
but I get errors every time, either "PATTERN must be a single string" (for the former) or "Undefined operator '~' for input arguments of type 'cell'" (for the latter).
Is there a way of using strfind, or any other function for that matter, to find a file who's name contains "PBS" but doesn't contain "flush"? Apologies, I feel like this should be super simple but I can't seem to find anything online. Of course I could re-consider my filenaming convention, but for the purposes of passing over data to the next person, it is useful to have ludicrously descriptive filenames.
Many thanks!
P.S. I have put matlab 2016a as the release but I also have 2018a.

채택된 답변

Amy Haskins
Amy Haskins 2018년 9월 18일
strfind returns the index of where the substring starts rather than a binary value. If the string you are searching for is not found, then empty is returned. Something like the following should work in both R2016a and R2018a:
if ~isempty(strfind(y{n}, 'PBS')) && isempty(strfind(y{n}, 'flush')) ...
In R2016b, a new function "contains" was introduced that makes this much easier because it just checks whether or not something is a substring.
if ~contains(y{n}, 'PBS') && contains(y{n}, 'flush') ...
If you want to vectorize your code, contains can accept a cell array and will return back a binary vector indicating which rows or columns contain the specified search string.
  댓글 수: 1
Clare
Clare 2018년 9월 18일
Hi Amy, perfect, should have realised! I'll try "contains" later when I move to 2018a, as perhaps it might be better to vectorise it, I'll see how it goes!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by