strfind issue

조회 수: 10 (최근 30일)
Robbie
Robbie 2011년 11월 29일
Hi,
I have a filename (including whole path) as a string with directories separated by / e.g. root/folder/file.
I am using strfind to find the slashes as follows and to give an index array of the position of the / symbols, :
% Find all occurances of the string '/'
[no_slash] = strfind ( line, '/' );
and then trying to extract the filename as a string as follows:
% Extract the case number:
caseNo = ( [no_slash(3)+1 : no_slash(3)+4] );
I get NaN returned and I don't know why! If anyone has an idea or an alternative method then it would be much appreciated!!
Thanks,
Robbie

채택된 답변

Matt Tearle
Matt Tearle 2011년 11월 29일
As Daniel says, there must be more going on. Can you copy the code directly? strfind returns the indices; if there are no matches, it returns []. Hence, if line was 'root/folder/file', strfind(line,'/') returns [5,12].
So in this case you'd get an indexing (out of bounds) error on the next line. If there was three slashes in the string, you'd get a vector like [13, 14, 15, 16].
Are you perhaps trying to extract a portion of the string and str2num it? In which case, you want
caseNo = str2double(line(no_slash(3)+1 : no_slash(3)+4))
(Note: if you leave out the line in the above command, you get NaN. Or if line isn't a string.)
  댓글 수: 2
Daniel Shub
Daniel Shub 2011년 11월 29일
Good call on the str2double returning NaN.
Robbie
Robbie 2011년 11월 29일
Yeah I got it working by adding in the 'line' thanks for your help it is much appreciated.

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

추가 답변 (1개)

Daniel Shub
Daniel Shub 2011년 11월 29일
The only way
[no_slash(3)+1 : no_slash(3)+4]
can be equal to NaN is if no_slash(3) is equal to NaN. You are not showing us something important because I am pretty sure that strfind does not return NaN.
All that said fileparts might help you out...
doc fileparts
  댓글 수: 3
Daniel Shub
Daniel Shub 2011년 11월 29일
What is no_slash equal to? Can you check that line is also a string. Please post a MWE with what line needs to be to get the error?
Robbie
Robbie 2011년 11월 29일
Thanks, I got it working from matt's suggestion (I left out the line) and it works fine now, I also got it working through fileparts. Your help is much appreciated:
caseNo = line(no_slash(3)+1 : no_slash(3)+4)

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by