Reputation: 31
I have a cell array that has strings in each row. I want to count the number of characters in each row of the cell array, including spaces. How do I do this in matlab?
Thanks for your answer, I'm a bit stuck though in my code
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)
I am ultimately trying to end up with a cell array that will store the name as a string in the first column and the second column will store the number of characters within the string as an integer. That would be the last bit of my code starting from cellarray2
Upvotes: 1
Views: 1324
Reputation: 30589
Say you have a cell array C
:
>> C = {'a','b2','c';'x','y','z';'aa','bb','cc'}
C =
'a' 'b2' 'c'
'x' 'y' 'z'
'aa' 'bb' 'cc'
Then use cellfun
and sum
:
>> charsPerRow = sum(cellfun(@numel,C),2)
charsPerRow =
4
3
6
Say you want to tag this on to the cell:
>> C2 = [C num2cell(charsPerRow)]
C2 =
'a' 'b2' 'c' [4]
'x' 'y' 'z' [3]
'aa' 'bb' 'cc' [6];
Upvotes: 2