1

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.

chappjc
  • 30,359
  • 6
  • 75
  • 132
WetlabStudent
  • 2,556
  • 3
  • 25
  • 39

1 Answers1

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.

chappjc
  • 30,359
  • 6
  • 75
  • 132
  • thanks a bunch, I did not know about the unique function. Thanks for letting me know about it. – WetlabStudent Nov 09 '13 at 20:21
  • @user1544793: Glad to help. Out of curiosity, did you want it the first way? – chappjc Nov 09 '13 at 20:22
  • That doesn't matter so much the plotting function won't care about the ordering as long as the pairing is consistent. Probably the sorted way is cleaner for other applications though. – WetlabStudent Nov 09 '13 at 20:23
  • @user1544793: I see. Sounds like you will be plotting against `unv`, which contains the sorted unique values in `v`, or against `unv(ivorder)` for the unique values in `v` in the order in which they appear in `v`. – chappjc Nov 09 '13 at 20:25