Clear Filters
Clear Filters

accumarray works with made up data, but not real data

1 view (last 30 days)
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!

Accepted Answer

Walter Roberson
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)];
  3 Comments
Walter Roberson
Walter Roberson on 25 Nov 2020
what is max(matA(:, 1)) and numel(unique(matA(:, 1))
Walter Roberson
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Reference Applications in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!