str2double conversion...

조회 수: 2 (최근 30일)
Aniya
Aniya 2016년 10월 25일
편집: Aniya 2016년 11월 11일
clc;
fid = fopen('fileName','r');
allText = textscan(fid,'%s','delimiter','\n')
allText = strfind(allText{1}, 'Num_X=');
strv =(find(~cellfun('isempty', allText)));% find position of Num_X
str = cell (11,1);
fseek(fid,0,-1);
for k = 1:11
str{k}= fgetl(fid);
end
W = str2double(str{strv});% trying to obtain number in that string.
Returns NaN .Why?
  댓글 수: 2
Steven Lord
Steven Lord 2016년 10월 25일
Set a breakpoint on the last line of code then run your code. When you reach that last line, what is the value of this expression?
str{strv})
You're encountering this behavior listed in the documentation.
If str2double cannot convert text to a number, then it returns a NaN value.
It would be interesting / informative to see what you're trying to convert, knowing that we may be able to offer a suggestion as to how to resolve the issue.
Aniya
Aniya 2016년 10월 26일
편집: Aniya 2016년 11월 11일
I forgot to specify the position in a string...Thank you for your effort...

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

채택된 답변

dpb
dpb 2016년 10월 25일
Because str{strv} will be a single character and equal to 'N' assuming the string 'Num_X=' is in the text in the first line; otherwise it'll be whatever character happens to be in that position in the line. fgetl returns a character array; subscripting it with a single index returns only a single character, not a full string as does a reference to a cell string. Of course, str2double and friends aren't cellstring aware.
textscan is probably a better approach to reading the file; let's see a small subset of the file format...
  댓글 수: 2
Aniya
Aniya 2016년 10월 26일
I need to specify the position in the particular string ....Ya ..I get it thank you so much for your support.
dpb
dpb 2016년 10월 26일
So show us the file...probably something like
...
l=fgetl(fid);
fscanf(l,'Num_X=%f')
or a variation thereon will directly parse the file format. Or, use textscan and can likely read the whole file or as many records as wanted without the loop and fgetl but no can help much w/o knowing what the file/record structure actually looks like.
Or, regular expressions can parse stuff, too, although I'm pretty much klewless on writing complex pattern-matching expressions therein...

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by