在Matlab中获得每个x位置的平均y值

时间:2013-03-18 14:41:06

标签: matlab

我不知道怎么说这个,只是一个例子:

x = [1 4 4 5 5 5];
y = [5 1 3 3 4 5];

然后我想输出

xs          = [1 4 5];
ys          = [5 2 4];
frequencies = [1 2 3]

(因为x = 1时的平均'y'是5,x = 4时的平均'y'是(1+3)/2 = 2,而x = 5时的平均'y'是{ {1}})。

我可以用笨拙的方式计算出来,但也许有一个很好的解决方案。

7 个答案:

答案 0 :(得分:4)

您可以使用直方图功能histc来获取每个类别:

x = [ 1 4 4 5 5 5];
y = [ 5 1 3 3 4 5];
xs = unique(x);
[frequencies xb] = histc(x, xs); % counts the number of each unique occurrence
ysp = sparse(1:numel(x), xb, y); % a sparse matrix is a good way to organize the numbers
ys = full(sum(ysp)./sum(ysp>0)); % each column in the matrix corresponds to a "index"

这为您提供了所需的三个阵列。我认为这是非常干净和高效的 - 没有循环,只有四行代码。

答案 1 :(得分:3)

x = [1 4 4 5 5 5];
y = [5 1 3 3 4 5];
xs = unique(x);
[frequencies,bin] = histc(x,xs);
ys = arrayfun(@(i) mean(y(bin==i)), 1:length(xs));

答案 2 :(得分:2)

@ioum的答案对我来说很有用,虽然在最后一行中有一个小错误,当我作为输入提供其他向量而不是在这里发布的那些时出现了。例如,在删除每个向量的最后一个元素后,答案应为:

ys = [5 2 3.5]

略微更正的代码是:

x = [1 4 4 5 5 5];
y = [5 1 3 3 4 5];
xs = unique(x);
[frequencies,bin] = histc(x,xs);
ys = arrayfun(@(i) mean(y(bin==i)), 1:length(xs));

我试图编辑@ioum的帖子,但编辑没有通过。

答案 3 :(得分:0)

我不确定这个解决方案是否会被认为足够优雅,但这应该有效:

x = [1 4 4 5 5 5];
y = [5 1 3 3 4 5];
[xs,I,J] = unique(x);    %The value of the index vector I is not required here.
ys = zeros(size(xs));
frequencies = zeros(size(xs));
for i = 1:max(J)
    I = find(J==i);
    ys(i) = mean(y(I));
    frequencies(i) = length(I);
end
xs,ys,frequencies

输出结果为:

xs =

     1     4     5


ys =

     5     2     4


frequencies =

     1     2     3

我希望这会有所帮助。

答案 4 :(得分:0)

x = [1 4 4 5 5 5]';
y = [5 1 3 3 4 5]';

%这可以更聪明地完成......

indexlong=accumarray(x,x,[],@mean)'
meanlong=accumarray(x,y,[],@mean)'
frequencieslong=accumarray(x,1)'

%遗漏了零

takethese=(indexlong>0);
xs=indexlong(takethese)
ys=meanlong(takethese)
frequencies=frequencieslong(takethese)

答案 5 :(得分:0)

这是我的代码,希望它有帮助...

   x=sort(x);
   ind=1;
    for i=1:length(x)
        if (i>1 && x(i)==x(i-1))
           continue;
        end
        xs(ind)=x(i);
        freq(ind)=sum((x==x(i)));
        ys(ind)=sum((x==x(i)).*y)/freq(ind);
        ind=ind+1;
    end

答案 6 :(得分:0)

虽然我会推荐一种直方图方法,但这是我在循环中的方法。与其他一些解决方案没那么太不同,但我相信它只是更好一些,所以我会发布它。

xs = unique(x)
for t = 1:length(xs)
   idx = x == xs(t);
   ys(t) = mean(y(idx));
   frequencies(t) = sum(idx);
end
相关问题