2012-10-28 57 views
2

您好我現在用的是下面的代碼從data.txt中Matlab的textscan出了錯:cellfun從某些行

fid = fopen('D:\data.txt','r'); 
A=textscan(fid,'%s %*s %f %s %f %s %*s %*s %*s %*s %*s %*s %*s %*s %*s,'Delimiter',','); 
fclose(fid); 
Loc = [A{[2, 4]}]; 
row_idxs = cellfun(@(s) strcmp(s, '$GPGGA'), A{1}); 
Loc = Loc(row_idxs, :); 
display(Loc); 

的代碼完美地工作,如果最後包含「GPGGA」線讀取某些值選擇數據data.txt中的行被刪除。不知道爲什麼當最後一行包含在文本文件中時會引發此錯誤。是什麼原因?我很困惑!

「???錯誤使用==> horzcat CAT參數尺寸並不一致 錯誤==>試驗在4 祿= [A - {[2,4]}。];」

的data.txt

$GPGSV,4,1,16,05,15,046,23,29,47,071,21,16,31,291,18,31,39,202,18*73 
$GPGSV,4,1,16,05,15,046,23,29,47,071,21,16,31,291,18,31,39,202,18*73 
$GPGSV,4,1,16,05,15,046,23,29,47,071,21,16,31,291,18,31,39,202,18*73 
$GPGSV,4,1,16,05,15,046,23,29,47,071,21,16,31,291,18,31,39,202,18*73 
$GPGSV,4,2,16,23,13,298,17,25,15,119,17,06,22,247,16,03,04,251,14*75 
$GPGSV,4,2,16,23,13,298,17,25,15,119,17,06,22,247,16,03,04,251,14*75 
$GPGSV,4,2,16,23,13,298,17,25,15,119,17,06,22,247,16,03,04,251,14*75 
$GPGSV,4,2,16,23,13,298,17,25,15,119,17,06,22,247,16,03,04,251,14*75 

$GPGGA,1.8,98.90,S,18.0014,E,1,04,1.0,87.8,M,48.0,M,,*76 
$GPGGA,1.3,98.91,S,18.0015,E,1,04,1.0,100.7,M,48.0,M,,*40 
$GPGGA,1.3,98.92,S,18.0016,E,1,04,1.0,105.4,M,48.0,M,,*4F 
$GPGGA,1.8,98.93,S,18.0017,E,1,04,1.0,87.8,M,48.0,M,,*76 
$GPGGA,1.8,98.94,S,18.0018,E,1,04,1.0,87.8,M,48.0,M,,*76 
$GPGSV,4,4,16,27,,,,26,,,,24,,,,22,,,*79 
+0

我的回答有幫助嗎?如果是這樣,那麼請標記回答的問題。否則,請告訴我是否有不清楚的地方,我可以嘗試改進我的答案。謝謝。 –

+0

的確是!非常感謝你!對於laaaaaaaaaate回覆抱歉! – user1658248

回答

1

你的格式字符串也是白搭。它僅表示15列。您發佈的示例數據有20列。我建議使用下面的代碼(運行沒有我的機器上的錯誤),而不是:

fid = fopen('D:\data.txt','r'); 
A=textscan(fid,'%s %*s %f %s %f %s %*[^\n]', 'Delimiter',','); 
fclose(fid); 
Loc = [A{[2, 4]}]; 
row_idxs = cellfun(@(s) strcmp(s, '$GPGGA'), A{1}); 
Loc = Loc(row_idxs, :); 
display(Loc); 

注意,在我的格式字符串的結構%*[^\n]。這告訴textscan忽略從這一點開始的所有列。它比反覆寫出大量%*s要乾淨得多。另外,這意味着在構建格式字符串時不太可能計算列的數量:-)