MatLab accumarray意外更改顺序 [英] MatLab accumarray unexpectedly changing ordering
问题描述
只要我了解accumarray,它的意思是使输出的第n行:1)在sub.中找到n.2)如果n在m1,m2中,则m3在sub中的元素,3)将函数应用于值4的第m1,m2,m3个元素,即输出的第n行"
As long as I understood accumarray, it means "Making the nth row of the output: 1) find n in sub. 2) if n is in m1, m2, m3 th element in sub, 3) apply the function to m1,m2,m3 th element of val 4) that's the nth row of the output"
我在某个地方错了吗?
Am I wrong somewhere?
我运行了以下代码.
A = [2 10 13 ; 1 11 14; 1 12 10]
[U,ix,iu]= unique(A(:,1))
vals = reshape(A(:, 2:end).', [], 1)
subs = reshape(iu(:, ones(size(A, 2)-1,1)).', [], 1)
r2 = accumarray(subs, vals', [], @(x){x'})
r2{1}
r2{2}
A =
2 10 13
1 11 14
1 12 10
U =
1
2
ix =
3
1
iu =
2
1
1
vals =
10
13
11
14
12
10
subs =
2
2
1
1
1
1
r2 =
[1x4 double]
[1x2 double]
ans =
12 11 14 10
ans =
13 10
=======================
=========================
但是我期望r{1} = 11 14 12 10
和r{2} = 10 13
.
accumarray为什么突然改变顺序?
Why did accumarray suddenly changed the ordering?
如何获得预期的结果?
推荐答案
注意:如果
subs
中的下标未排序,则fun
不应依赖 按其输入数据中值的顺序.
Note If the subscripts in
subs
are not sorted,fun
should not depend on the order of the values in its input data.
并且您的subs
未排序(至少不是按升序排列).如果您重写代码,以便对subs
进行排序并相应地重新排列vals
,您将获得所需的结果:
And your subs
is not sorted (at least not in ascending order). If you rewrite the code so that subs
is sorted and vals
is also rearranged accordingly you get the desired result:
A = [2 10 13 ; 1 11 14; 1 12 10]
[U,ix,iu]= unique(A(:,1))
vals = reshape(A(:, 2:end).', [], 1)
subs = reshape(iu(:, ones(size(A, 2)-1,1)).', [], 1)
[subs_sorted, I] = sort(subs);
r2 = accumarray(subs_sorted, vals(I)', [], @(x){x'})
r2{1}
r2{2}
运行此代码将返回:
ans =
11 14 12 10
ans =
10 13
这篇关于MatLab accumarray意外更改顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!