math - 如何找出 y 中每组数字的平均值,这些数字在 x 中具有相同的索引?

标签 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(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

我的问题是在循环中使用两个以上的计数器。也许,我应该写这样的东西:

s=1:8
for k=1:9
if x(k)=x(k+s);
else
s=s+1;
end
end

这没用:( 如果有任何帮助或建议,我将不胜感激!

最佳答案

如果我没理解错的话,您想要的是在“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);

关于math - 如何找出 y 中每组数字的平均值,这些数字在 x 中具有相同的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8510168/

相关文章:

python - python 中的 slider

algorithm - 顺序搜索分析

c# - 具有负值的最短路径的最快算法?

c - matlab 中 mex 函数的安全、快速 CFLAGS

c# - 如何将 int 数组转换为 int?

algorithm - 在具有一组连续 1 的二维数组中查找所有可能的位排列

matlab - 一个类似于Matlab GrayThresh的OpenCV函数

java - 将 Matlab 的 FFT 移植到 native Java

matlab - 在 MATLAB 中,给定数据向量,查找阈值内的零交叉

matlab - 在 MATLAB 中开始使用 JeroMQ