How to deal with paired values?

混江龙づ霸主 提交于 2019-12-08 05:50:42

问题


Say I have a vector of independent variable values

v =[ 1 2 2 1 1 .5 1 2 .5 .5 1]

and a vector of response variables

u = [ 5 22 20 4 8 .2 5 12 0 .5 6]

I want to plot u vs. v with errorbars, the method needs to work for 100s of possible values for the independent variable. The problem isn't in plotting the error bars, it's in how can I create a vector pair [mean(u(find(v==0.5)), mean(u(find(v==1)), mean(u(find(v==2))]. Is there a standard automated way of doing this other than sorting v, then picking out the values of sorted v and finding the index of v where v matches those values? This seems very inefficient.


回答1:


This might be what you are after if you want to get the means for each unique value of v in the order in which the unique values appear in v:

>> [unv,iunv,iv] = unique(v);
>> umeans = accumarray(iv(:),u,[],@mean);
>> [~,ivorder] = sort(iunv);
>> umeans = umeans(ivorder)

umeans =

    5.6000
   18.0000
    0.2333

If you want the means in order of the sorted values of v, then just use the output of accumarray without the reordering commands:

>> [unv,iunv,iv] = unique(v);
>> umeans = accumarray(iv(:),u,[],@mean)

umeans =

    0.2333
    5.6000
   18.0000

Just ensure that u is a row vector.



来源:https://stackoverflow.com/questions/19882413/how-to-deal-with-paired-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!