【问题标题】:Counting the number of characters in a row of a cell array, including spaces?计算单元格数组的一行中的字符数,包括空格?
【发布时间】: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


【解决方案1】:

假设你有一个元胞数组C

>> C = {'a','b2','c';'x','y','z';'aa','bb','cc'}
C = 
    'a'     'b2'    'c' 
    'x'     'y'     'z' 
    'aa'    'bb'    'cc'

然后使用cellfunsum

>> 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];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 2022-10-14
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多