MATLAB: Find sum of max values in matrix subject to constraints

max valueoptimise

Hi I would greatly appreciate help on the following question. I have two matrices, a and b: a = [0 0 3 ; 0 7 2 ; 5 0 1 ] ; , with a representing yields; and b = [1 2 3 ; 1 2 100 ; 1 100 100 ] ; representing tenors.
I would like to find the highest combined value from a, subject to the sum of the coinciding values in b not exceeding three.
So the answer here would be 12, because the sum of 7+5 = 12, and the coinciding sum of b values would be 2+1 = 3.
Like i say any help at all would be greatly appreciated.

Best Answer

a = [0 0 3 ; 0 7 2 ; 5 0 1 ] ;
b = [1 2 3 ; 1 2 100 ; 1 100 100 ] ;
[first_max, ind] = max(a(:));
[m1, n1] = ind2sub(size(a),ind);
c = a;
c(m1,n1) = 0;
[second_max, ind] = max(c(:));
[m2,n2] = ind2sub(size(c),ind);
sum1 = a(m1,n1) + a(m2,n2)
if b(m1,n1) < 3 & b(m2,n2) < 3
sum2 = b(m1,n1) + b(m2,n2)
end