Arrays 如何在matlab中求数组中每个单词的长度

Arrays 如何在matlab中求数组中每个单词的长度,arrays,matlab,Arrays,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.Fo

我正在编写这段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。有人能帮我解决这个问题吗?提前谢谢。

temp1
是一个
单元
数组。应该使用大括号索引提取单个字符串,如下所示

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

cellfun(@length,temp1)
表示short或
cellfun('length',temp1)
表示short&fast;)我还有一个疑问。我可以检索每个单元格的内容,并能够进行一些处理(即将每个单词转换为关键字,即happiness->happi,end->end等)。我可以对除最后一个单词以外的所有单词进行处理。但是,当我在最后一个词“幸福”和句号之间加上一个空格时,它起了作用。你能解释一下为什么会发生这种情况以及可能的解决办法吗?因为我认为在一个有用户交互的现实项目中,我不认为用户可以坚持在最后一个单词和句点之间保留空格。@sebastian您是否有一个链接解释为什么使用字符串比函数句柄快?@dan nope-但是所有的“字符串”-cellfun版本(来自文档中的“向后兼容性”部分)明显快于其对应的函数句柄。最明显的原因是,它们跳过了函数句柄调用开销,更直接地调用了内部
length
isempty
等函数。