How do I stop accumarray adding rows for non-existent values of the index column?

I want to sum the values in one column of an array based on values in another (index) column. What I get is a row for all values up to the maximum in the index column. For example,
a = [2 1.1; 2 1.2; 4 1.3; 4 1.4]
b = accumarray(a(:,1),a(:,2))
doesn't give what I expect: b =
2.3000 % i.e. sum of values for which the index is 2
2.7000 % i.e. sum of values for which the index is 4
but
b =
0
2.3000
0
2.7000
How do I suppress the rows where the index value doesn't exist? This is a trivial example, but in what I'm trying to do the index values are in the range 195001 to 202012 so I get a large number of zeros. All help gratefully received...

 Accepted Answer

unique the first column and use the third output in accumarray instead of the first column of a.
a = [2 1.1; 2 1.2; 4 1.3; 4 1.4];
b = accumarray(a(:,1),a(:,2))
[c1, ~, c3] = unique(a(:, 1));
d = accumarray(c3, a(:, 2))
results = table(c1, d, 'VariableNames', {'elementInAcolumn1', 'accumulatedValue'})
I assembled the results into a table to more easily show the relationship between c1 and d.

1 Comment

Great answer, solved my problem and I understand unique and table a bit better now too! Many thanks.

Sign in to comment.

More Answers (1)

a = [2 1.1; 2 1.2; 4 1.3; 4 1.4];
[~, ~, group] = unique(a(:, 1));
b = accumarray(group, a(:,2))

Categories

Asked:

on 14 Jul 2017

Commented:

on 14 Jul 2017

Community Treasure Hunt

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

Start Hunting!