2014-01-29 65 views
1

我正在研究這個matlab代碼,它是從文本文檔讀取內容並將單詞存儲到數組中,並查找每個單詞的長度。下面是我的代碼:如何在matlab中查找數組中每個單詞的長度

file1=fopen('doc1.txt','r'); 
%file 1 is now open 
%read data from file 1 
text1=fileread('doc1.txt'); 
%now text1 has the content of doc1 as a string.Next split the sentences 
%into words.For that we are calling the split function 
temp1=strsplit(text1,' '); 
[r,c]=size(temp1); 
disp('The total number of distinct words in the document are ') 
c 
disp('And those words are :') 
for i=1:c 
    k= temp1(i) 
    length(k) 
end 

這裏不管每個單詞的長度是多少,長度(K)總是提前1顯示有人可以幫我解決這個感謝?

回答

2

temp1是一個cell數組。你應該使用大括號索引提取單個字符串,就像這樣

words = 'foo bar1 baz23'; 
temp1 = strsplit(words, ' '); 
for i = 1:numel(temp1) 
    k = temp1{i} 
    length(k) 
end 
+0

非常感謝你!!它的工作。 –

+0

或'cellfun(@length,temp1)'爲簡短 – Dan

+1

或'cellfun('length',temp1)'爲short&fast;) – sebastian

相關問題