updating/inserting summary array

1 view (last 30 days)
joh
joh on 7 May 2014
Commented: joh on 7 May 2014
hi, i have a summary array where it keeps a count of repeated items. e.g
sumarray = {'red', 2; ...
'blue', 3}
etc. While running a for loop, if a red item appears, I simply want to increment the count to 3 for 'red', if a new category comes in e.g. 'pink' I simply want to add a new row {'pink',1}. What is the most efficient way to implement this?
Thanks.
  1 Comment
Cedric
Cedric on 7 May 2014
Edited: Cedric on 7 May 2014
Are the colors or words that you want to count stored in a cell array as well (as individual words), or are they in a "stream" of text?

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 7 May 2014
You can use ismember() to check if it's in the list. If it is, increment the second column, if it's not, append it on to the end with a count of 1. See demo code below:
sumarray = {'red', 2; ...
'blue', 3}
% Pick one or the other (red or pink) to test the code.
testWord = 'red'
testWord = 'pink'
column1 = sumarray{:,1}
rowIndex = ismember(testWord, column1, 'rows')
if rowIndex >= 1
sumarray{rowIndex,2} = sumarray{rowIndex, 2} + 1;
else
% Not in there yet. Add it to the end
sumarray{end+1,1} = testWord;
sumarray{end,2} = 1;
end
% See what we ended up with
sumarray

More Answers (1)

Cedric
Cedric on 7 May 2014
Edited: Cedric on 7 May 2014
You would have to test, but here is what I guess is an efficient solution:
colors = {'red', 'black', 'red', 'green', 'red', 'green', 'red'} ;
[uc,~,ic] = unique( colors ) ;
counts = accumarray( ic, 1 ) ;
sumarray = [uc.', num2cell(counts)] ;
For the given dummy set of colors, this outputs
>> sumarray
sumarray =
'black' [1]
'green' [2]
'red' [4]

Categories

Find more on Numeric Types in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!