accumarray works with made up data, but not real data

1 回表示 (過去 30 日間)
France Poirier
France Poirier 2020 年 11 月 25 日
コメント済み: Walter Roberson 2020 年 11 月 25 日
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 日
what is max(matA(:, 1)) and numel(unique(matA(:, 1))
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 Center および File ExchangeReference Applications についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by