Sum of Cells next to a String
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
tonito
am 4 Apr. 2015
Beantwortet: Image Analyst
am 4 Apr. 2015
Hi all,
I imported an excel sheet of numbers next to a string (a category) in an array and having trouble finding a way to get the sum of all the numbers under a category. For example:
Let's say I want the sum of all the numbers to the right of 'VLGMC' and 'DLG'. Is there a way I could do this?
Thanks,
Tony
0 Kommentare
Akzeptierte Antwort
Mohammad Abouali
am 4 Apr. 2015
Bearbeitet: Mohammad Abouali
am 4 Apr. 2015
% creating sample data
data={'VLGMC', 1, 'DLG', 4, 'a', 7; ...
'VLGMC', 2, 'c', 5, 'a', 8; ...
'b', 3, 'DLG', 6, 'a', 9};
% summing numbers next to VLGMC
mask=strcmpi(data,'VLGMC');
[row,col]=find(mask);
idx=sub2ind(size(data),row,col+1);
sum_VLGMC=sum(cell2mat(data(idx)))
sum_VLGMC =
3
% summing numbers next to DLG
mask=strcmpi(data,'DLG');
[row,col]=find(mask);
idx=sub2ind(size(data),row,col+1);
sum_DLG=sum(cell2mat(data(idx)))
sum_DLG =
10
The code would be much easier if you have all your text on one column and the numbers on a second column.
0 Kommentare
Weitere Antworten (1)
Image Analyst
am 4 Apr. 2015
Try using readtable() then summing the column(s). I'd have done a little for you but you forgot to attach your workbook.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Cell Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!