accumarray works with made up data, but not real data

1 次查看(过去 30 天)
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
Walter Roberson 2020-11-25
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 个评论
Walter Roberson
Walter Roberson 2020-11-25
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Reference Applications 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by