# Re: find the maximum sum of a subset of a matrix

Jim Robison-Cox (jimrc@mathfs.math.montana.edu)
Tue, 27 Jan 1998 16:35:36 -0700 (MST)

On Tue, 27 Jan 1998, haeberli wrote:

> I have a simple (simle looking?) problem for which I can't get an easy
> solution:
>
> I have a matrix like
>
> a11 a12 a13 a14....
> a21 a22 a23 a24....
> . . . .
> . . . .
>
> I want to determine those five elements in this matrix, which produce the
> maximum sum.
>

So you're just looking for the 5 largest values in the matrix?
That would be easy, assuming matrix A contains n elements,

A[order(A)[(-4:0)+n]]

> A <- matrix(rnorm(20),4,5)
> A
[,1] [,2] [,3] [,4] [,5]
[1,] 0.008629 -0.36035 -0.0003541 0.9163 0.9026
[2,] -0.038239 -0.03375 1.2066771 -1.3830 -1.1559
[3,] -1.016802 -1.88316 -0.0204049 -0.4696 0.1050
[4,] -0.132446 0.33684 -1.0119329 -0.8036 0.2302
> A[order(A)[(-4:0)+20]]
[1] 0.2302 0.3368 0.9026 0.9163 1.2067

But I'm not sure that you just wanted the elements, maybe you wanted
their positions in A?

Jim Robison-Cox ____________
Department of Math Sciences | | phone: (406)994-5340
2-214 Wilson Hall \ BZN, MT | FAX: (406)994-1789
Montana State University | *_______|
Bozeman, MT 59717 \_| e-mail: jimrc@math.montana.edu