我有一个单元格数组,每行都有字符串。我想计算单元格数组每行中的字符数,包括空格。我如何在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
开始的代码的最后一点答案 0 :(得分:2)
假设您有一个单元格数组C
:
>> C = {'a','b2','c';'x','y','z';'aa','bb','cc'}
C =
'a' 'b2' 'c'
'x' 'y' 'z'
'aa' 'bb' 'cc'
然后使用cellfun
和sum
:
>> charsPerRow = sum(cellfun(@numel,C),2)
charsPerRow =
4
3
6
假设您要将此标记为单元格:
>> C2 = [C num2cell(charsPerRow)]
C2 =
'a' 'b2' 'c' [4]
'x' 'y' 'z' [3]
'aa' 'bb' 'cc' [6];