【发布时间】:2013-12-21 10:22:29
【问题描述】:
我有一个单元格数组,每行都有字符串。我想计算单元格数组每行中的字符数,包括空格。如何在 matlab 中执行此操作?
感谢您的回答,虽然我的代码有点卡住了
fid = fopen('thenames.txt', 'w');
if fid ~= -1
disp (' The file opened sucessfully')
else
disp (' The file did not open sucessfully')
end
string1 = input('Enter a name:','s');
countstr =1;
fprintf(fid, 'Name %d is %s\n', countstr, string1)
TF = strcmp ('stop', string1);
while TF == 0;
countstr = countstr+1;
string1 = input ('Enter a name:','s');
TF = strcmp ('stop', string1);
if TF ==0
fprintf(fid, 'Name %d is %s\n', countstr, string1)
elseif TF == 1
disp ('Ok. No more names')
end
end
totalnames = countstr - 1;
fprintf(fid, 'There were %d total names given\n', totalnames)
fid = fopen('thenames.txt');
if fid ~= -1
disp (' The file opened sucessfully')
else
disp (' The file did not open sucessfully')
end
cellarray2 = [];
cellarray2 = textscan (fid ,'%s %d %s %s');
newcellarray = {cellarray2{4}}
charsPerRow = sum(cellfun(@numel,newcellarray),2)
我最终试图得到一个单元格数组,它将名称作为字符串存储在第一列中,第二列将字符串中的字符数存储为整数。那将是我从 cellarray2 开始的代码的最后一点
【问题讨论】:
-
能把
newcellarray的内容吐出来吗? -
你应该做
newcellarray = cellarray2{4}而不是newcellarray = {cellarray2{4}}否则它是一个单元格数组中的一个单元格数组。然后你可以使用cellfun,如图所示。然后按照我更新的答案添加字符数列。 -
没问题。如果我的 cmets 和回答对您有所帮助,如果您愿意接受甚至投票,我将不胜感激。谢谢!
标签: arrays string matlab character cell