Effacer les filtres
Effacer les filtres

Find sum of max values in matrix subject to constraints

1 vue (au cours des 30 derniers jours)
Seamus
Seamus le 15 Juil 2015
Commenté : bio lim le 17 Juil 2015
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.
  2 commentaires
Grzegorz Lippe
Grzegorz Lippe le 15 Juil 2015
Modifié(e) : Grzegorz Lippe le 15 Juil 2015
Hello Seamus,
a nice riddle :)
A = [0 0 3 ; 0 7 2 ; 5 0 1 ] ;
B = [1 2 3 ; 1 2 100 ; 1 100 100 ] ;
siz = size(A) ;
b = B(:) ;
a = A(:) ;
[b1, b2] = meshgrid(b, b) ;
[a1, a2] = meshgrid(a, a) ;
% Sum up all possiblities, but only once
AA = triu(a1) + triu(a2) ;
BB = triu(b1) + triu(b2) ;
SIZ = size(AA) ;
% The sum of B must be less 4
validIdsofBB = triu(BB < 4) ;
% Find the maximum of all combined values in A, but only valid in B
[~, myID] = max(AA(:) .* validIdsofBB(:)) ;
%%The answer to the question:
AA(myID)
%%The Indizes to the original vectors:
[I,J] = ind2sub(SIZ,myID) ;
a(I)
a(J)
%%The Indizes to the original matrix
[i1,i2] = ind2sub(siz,I) ;
[j1,j2] = ind2sub(siz,J) ;
A(i1, i2)
A(j1, j2)
Seamus
Seamus le 15 Juil 2015
Gregor, that's absolute genius. Really, I thought i would have to loop and do this iteratively looking for something that met the right conditions. Thank you very much!

Connectez-vous pour commenter.

Réponse acceptée

bio lim
bio lim le 15 Juil 2015
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
  2 commentaires
Seamus
Seamus le 15 Juil 2015
Hi coffee murun, thanks a million for this. I had one follow up question on this. Is there an else statement that you can write which would repeat the initial part of the code in order to satisfy the below 3 constraint?
bio lim
bio lim le 17 Juil 2015
Hi, my pleasure. Do you mean in a way that you can insert any input and get the expected results?

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Descriptive Statistics and Visualization dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by