|
"Ulrik Nash" <uwn@sam.sdu.dk> wrote in message <hnav56$o8e$1@fred.mathworks.com>...
> Hi Everyone,
>
> Suppose I have a column vector
>
> A =
> 1
> 2
> 3
> 4
> 5
>
> And also a matrix
>
> B =
>
> 1 10
> 3 22
> 2 12
> 4 13
>
> Now I wish to create a matrix C, which has A as its first column, and the sum of the second column in B for those values found in B's first column:
>
> C =
> 1 10
> 2 12
> 3 22
> 4 13
> 5 0
>
> How would I do this?
>
> Regards,
>
> Ulrik.
Here is the more general approach:
% some data
A = [10 20 30 40 50 80].' ;
B = [10 1 ; 20 2 ; 10 3 ; 30 4 ; 30 5 ; 50 6 ; 999 999]
% engine
[tf,loc] = ismember(B(:,1),A)
sumB = accumarray(loc(tf),B(tf,2),[numel(A) 1]) ;
C = [A(:) sumB(:)]
If the first column of A only has integers between 1 and numel(A), a single call to accumarray would do, thereby omitting ISMEMBER:
A = 1:5 ; B = [ 1 10 ; 3 20 ; 5 30 ; 3 40] ;
C = [A(:) accumarray(B(:,1),B(:,2),[numel(A),1])]
hth
Jos
|