From: Ulrik Nash on
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.
From: someone on
"Ulrik Nash" <uwn(a)sam.sdu.dk> wrote in message <hnav56$o8e$1(a)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.

How did you get the second column of C? Its not clear (at least to me) how to follow your instructions and get your example solution.
From: Jos (10584) on
"Ulrik Nash" <uwn(a)sam.sdu.dk> wrote in message <hnav56$o8e$1(a)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
From: Ulrik Nash on
[How did you get the second column of C? Its not clear (at least to me) how to follow your instructions and get your example solution]

The values in second column of C represents the sums of the second column of B, for each of the numbers in B's first column. The value next to 5 is 0 because there are no values of 5 in B's first column.

I hope I am making sense! :-)

Regards,

Ulrik.
From: Jan Simon on
Dear Ulrik!

> 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

Following your example data, there is no sum - in opposite to the text description and the subject. Currently it looks like you search the indices of elements, which appear in two vectors - INTERSECT can help, if there are no repeated values.

Kind regards, Jan