Error Using Accumarray, Third input SZ must be a full row vector with one element for each column of SUBS

6 次查看(过去 30 天)
Hi All, I am having trouble using accumarray. I am getting the following error and I am having trouble figuring out why. Thanks in advance.
Error using accumarray Third input SZ must be a full row vector with one element for each column of SUBS.
Error in approach2 (line 13) p = accumarray(subs, val, sz);
And the following is the code:
d = [3 3 4 4 4 5 6 5 5 4 3 2 3 4 3 2 5 6 6 5 5 4 3];
precision = 1;
f = (round(d/precision)).*precision;
[c, ~, ic] = unique(f);
N = numel(c);
subs = [ic(1:end - 3), ic(2:end-2), ic(3:end-1), ic(4:end)]; val = 1; sz = [N^2, N^2];
p = accumarray(subs, val, sz);
p = bsxfun(@rdivide, p, sum(p, 2));

回答(2 个)

Star Strider
Star Strider 2015-7-27
If you don’t want to use the third argument, you don’t need to include it.
See if substituting this for your accumarray call does what you want:
p = accumarray(subs, val);

Walter Roberson
Walter Roberson 2015-7-27
编辑:Walter Roberson 2015-7-27
When you use accumarray, each row of subs is used as an index into array, as if
idx = num2cell(subs(K,:));
result(idx{:}) = val(K);
Your subs is 4 wide, so you are asking to create a 4 dimensional array.
My guess is that you want sz = [N, N, N, N]
You could always reshape() the result to N^2 x N^2
  1 个评论
Walter Roberson
Walter Roberson 2015-7-28
subs_sq = [(subs(:,2) - 1)*N + subs(:,1), (subs(:,4) - 1)*N + subs(:,3)];
p = accumarray(subs_sq, val);
p = bsxfun(@rdivide, p, max(1,sum(p, 2)));
Or alternately,
p = reshape(accumarray(subs, val, [N, N, N, N]), [N^2, N^2]);
p = bsxfun(@rdivide, p, max(1,sum(p, 2)));
Yes this does create a temporary 4-dimensional array, and then immediately reshapes it to 2D. It also has exactly the same effect as the subs_sq version that builds the 2D array directly by assigning a number to each possible 2D vector.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by