Math 我怎样才能找出y中的每组数字的平均值,它们在x中有相同的索引?

Math 我怎样才能找出y中的每组数字的平均值,它们在x中有相同的索引?,math,matlab,Math,Matlab,我想为两个矩阵编写这样的代码: x=[1 1 1 2 2 3 3 3 3]'; y=[11 21 31 24 32 33 13 37 3]'; 我怎样才能找出y中的每组数字的平均值,它们在x中有相同的索引 我的算法可以如下所示: If x(1)=x(2) counter1=1 sum1=y(1)+y(2) x(2)=x(3) counter1=2 sum1=sum+y(3) Define newx1=x(1) newy1=sum1/counter1 x

我想为两个矩阵编写这样的代码:

x=[1 1 1 2 2 3 3 3 3]';
y=[11 21 31 24 32 33 13 37 3]';
我怎样才能找出y中的每组数字的平均值,它们在x中有相同的索引

我的算法可以如下所示:

If     x(1)=x(2) counter1=1 sum1=y(1)+y(2) 
       x(2)=x(3) counter1=2 sum1=sum+y(3)  Define  newx1=x(1) newy1=sum1/counter1
       x(3)<>x(4) 
       x(4)=x(5) counter2=1 sum2=y(4)+y(3)  Define  newx2=x(4) newy2=sum2/counter2
       x(5)<>x(6) 
       x(6)=x(7) counter3=1 sum3=y(6)+y(7)  
       x(7)=x(8) counter3=2 sum3=sum+y(8)  
       x(8)=x(9) counter3=3 sum3=sum+y(9)  Define  newx1=x(6) newy3=sum3/counter3
这不起作用:(
如果我理解正确,我将非常感谢您的任何帮助或建议。

如果我理解正确,您需要在“x”中具有相同索引的每组数字的平均值。在这种情况下

function FindAverages
x=[1 1 1 2 2 3 3 3 3]';
y=[11 21 31 24 32 33 13 37 3]';

means = [];
indexes = unique(x);
for i=1:numel(indexes)
    index = indexes(i);
    indexInY = (x==index);
    means(end+1) = mean(y(indexInY));
end
disp(means);
一种解决方案是使用统计工具箱中可用的函数。它可以按组应用函数:

x=[1 1 1 2 2 3 3 3 3]';
y=[11 21 31 24 32 33 13 37 3]';
grpstats(y,x,@mean)
另一种选择(例如,如果您没有统计工具箱)是在FileExchange上使用提交。它将与特定类别对应的数字放入单元格数组中的单独单元格中。然后,您可以应用许多功能,包括CELLFUN的平均值:

cellfun(@mean,group2cell(y,x))

如果我正确理解了您的问题,您可以简单地使用accumarray,它应该比循环更快

%#Input
x=[1 1 1 2 2 3 3 3 3]';
y=[11 21 31 24 32 33 13 37 3]';

[newx, idx]=unique(x,'legacy');
newy=accumarray(x(:),y(:),[],@mean);  %#groups every element of 'y' according to the index of 'x' and applies the function '@fun' to each group.
%#Output
newy =[21.0000 28.0000 21.5000];
newx=[1 2 3];     %#returns the index used for each group
idx=[3 5 9];      %#returns the index of the last observation for each group

这对我来说毫无意义。你能澄清一下你想做什么吗?另外,你知道Matlab有一个高度优化的
mean
函数,对吗?@PengOne谢谢你的回答。是的,我知道matlab的平均函数,但我必须创建自己的函数,我可能会改变它。所以,我想做的是从x中创建另一个矩阵xnew=[1 2 3],只得到一个相等的矩阵和一个ynew=[(11+21+31)/3(24+32)/2(33+13+37+3)/4]我能更好地解释吗?
%#Input
x=[1 1 1 2 2 3 3 3 3]';
y=[11 21 31 24 32 33 13 37 3]';

[newx, idx]=unique(x,'legacy');
newy=accumarray(x(:),y(:),[],@mean);  %#groups every element of 'y' according to the index of 'x' and applies the function '@fun' to each group.
%#Output
newy =[21.0000 28.0000 21.5000];
newx=[1 2 3];     %#returns the index used for each group
idx=[3 5 9];      %#returns the index of the last observation for each group