# accumarray works with made up data, but not real data

1 view (last 30 days)
France Poirier on 25 Nov 2020
Commented: Walter Roberson on 25 Nov 2020
I am trying to write a code that does two things:
1. Counts the number of unique values by category
2. Couts the number of unique values by category if the value in another array is equal to 1.
I found some code online and adapted it. It works when I use just made up code. But it doesn't work when I use my actual data. The error message I get is that the "Dimensions of arrays being concatenated are not consistent.".
Here is my made up code:
matA = randsrc(30,1,[1,2,3;0.1,0.4,0.5]); This just creates an array of size 30 of 1,2, and 3 where 10% are 1s, 40% are 2s, and 50% are 3s.
matB = randsrc(30,1,[1,0;0.3,0.7]); This creates the second matrix of the same size of ones and zeros
n = size(matA, 1);
weights = ones(n, 1);
OT = unique(matA(:, 1));
OT = [OT, accumarray(matA(:,1), matB == 1)];
This code does exacty what I need.
When I substitute my actual data instead of matA and matB, I get an error. Both actual matrices are the same size: 100165x 1. Here is the output:
sizeA =
100165 1
sizeB =
100165 1
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
Error in CMAsickcount (line 14)
OT = [OT, accumarray(matA(:,1), matB == 1)];
What am I missing? I would be grateful for any suggestions.
Thank you!

Walter Roberson on 25 Nov 2020
OT = unique(matA(:, 1));
That will have length equal to the number of unique values
OT = [OT, accumarray(matA(:,1), matB == 1)];
The accumarray will output with length according to the maximum unique value, not according to the number of unique values.
[OT, ~, G] = unique(matA(:, 1));
OT = [OT, accumarray(G, matB == 1)];

France Poirier on 25 Nov 2020
the code does work and does what I need it to do. Thank you very much, I really apreciate it. But I still don't understand why my original code workde with an array of size 30 and 3 unique elements, but not with an array of size 100165 and some 49000 unique elements...
Walter Roberson on 25 Nov 2020
what is max(matA(:, 1)) and numel(unique(matA(:, 1))
Walter Roberson on 25 Nov 2020
Remember that the size of the output returned by accumarray is not based on the number of unique values in the first parameter ("subscript"), and is instead determined by the maximum value of the first parameter.