|
"jenya polyakova" <jenya56@yahoo.com> wrote in message <h9be7r$gh5$1@fred.mathworks.com>...
> I know it can be done in one line. But I am not sure how to do it. Anybody please?
> I have a matrix. Say,
> col1 col2
> 23 0.6
> 12 0.9
> 12 1.0
> 23 0.5
> how to average col2 so that it averages by the same id number represented by col1 i.e it should give me the column of [(0.6+0.5)/2 ; (0.9+1.0)/2]. Thanks so much.
>
>
Assuming col1 is exactly integer so we can use it in boolean tests:
>> mean([col2(col1==23), col2(col1==12)]) % assumes equal numbers of each id
A more robust method would use round(col1) for the boolean. If you want some truly horrendous notation that keeps everything on one line and references only one matrix:
>> A = [23 0.6 ; 12 0.9 ; 12 1.0 ; 23 0.5]
>> [mean(A(round(A(:, 1))==23, 2)), mean(A(round(A(:, 1))==12, 2))]
% mean called twice
Good luck parsing that. It would be wiser to explicitly pull out the indices instead:
>> id1 = round(23);
>> id2 = round(12);
>> col1 = round(A(:, 1));
>> col2 = A(:, 2);
>> k1 = col1 == id1;
>> k2 = col1 == id2;
>> [mean(col2(k1)), mean(col2(k2))]
Hope this helps.
--
|