Labview and Matlab for PT

Just a place to discuss with Matlab and Labview

ad

失誤?!

今天試圖來做一個檔案處理,預備將我要的檔案形式讀入,我的檔案很簡單,如下:

name 腿長 腳踝長
SYC 47 19
YFT 41 13
ZJY 45 15
LSP 44 14
CCH 51 16
LIU 42 14.5
KMY 40 14
LC 41 13.5
LGP 46 15
CCL 40 13.5
CIC 49 16
ZKY 48 15


  這是在記事本或是notepad顯示的資料,前面是姓名並且腿長和腳踝長中間以'\t'做區隔。
  
  我的目的是要將檔案如matlab中textread指令一樣,將資料讀入並以name Leg Ankle,三個陣列儲存,然後第一行不要。



clear all
fd = fopen('I:\Leglength.txt','r');
m = 1;
n = 1;
while 1
if m == 1
tile = fgets(fd);
m=m+1;
elseif fgets(fd) == -1
break
else
content=fgets(fd);
[name(n) Leg(n) Ankle(n)]=strread(content,'%s %f %f');
n=n+1;
end
end
fclose(fd);



  想法非常簡單m=1單純就用在第一行,然後把第一行資料丟到title裡面去。其他就是[name(n) Leg(n) Ankle(n)]=strread(content,'%s %f %f');依照這樣格式丟入,然後如果讀到最後一行fgets(fd) == -1,則結束此程式。

  執行後結果,以name來看



>> name

name =

'YFT' 'LSP' 'LIU' 'LC' 'CCL' 'ZKY'



  哇哩勒,what happened??為啥麼只讀了3 5 7 9 11 13行,發生了啥事?百思不得其解,試了又試,情況依舊,於是我開始懷疑起elseif fgets(fd) == -1,所以我把程式改寫成



clear all
fd = fopen('I:\Leglength.txt','r');
m = 1;
n = 1;
while 1
content = fgets(fd)
if m == 1
tile = content;
m=m+1
elseif ischar(content) == 1
[name(n) Leg(n) Ankle(n)]=strread(content,'%s %f %f');
n=n+1;
end
if content == -1
break
end
end
fclose(fd);




  果不其然,這次完全沒有問題




>> name

name =

'SYC' 'YFT' 'ZJY' 'LSP' 'CCH' 'LIU' 'KMY' 'LC' 'LGP' 'CCL' 'CIC' 'ZKY'





  那也就是說,把elseif fgets(fd) == -1當作判斷句的時候,程式就會讀了一行,所以在跑之後的[name(n) Leg(n) Ankle(n)]=strread(content,'%s %f %f'),所讀到的就是下一行檔案內的東西!

0 意見: