Find the indices of elements of matrix that were multiplied

2 vues (au cours des 30 derniers jours)
Astrik
Astrik le 15 Sep 2016
I have a task to find the maximum product of elements in a matrix. The input arguments are the matrix and the scalar n that tells me how many elements to multiply. If n=2, then I should multiply two by two. The maximum product can lie either in rows, or in columns on in diagonal. For example in this case A's elements were multiplied 2 by 2 along rows (B) and columns (C).
A =
8 1 6
3 5 7
4 9 2
B =
8.0000 6.0000
15.0000 35.0000
36.0000 18.0000
C =
24.0000 5.0000 42.0000
12.0000 45.0000 14.0000
I do it using the loop
c=[]
for ii = 1:(length(A)-n+1)
p = prod(A(:,ii:ii+n-1));
c=[c p];
end
or
for i=1:size(A,2)
B(i,:)=real(exp(conv(log(A(i,:)),ones(1,n),'valid')));
C(:,i)=real(exp(conv(log(A(:,i)),ones(1,n),'valid')));
end
In both cases I receive the product but when it comes to getting the maximum among that products, (in my case that is the product of A(3,1)*A(3,2)=45) I cannot find the indices of original matrix elements that formed that product. Any help will be appreciated.

Réponses (1)

Andrei Bobrov
Andrei Bobrov le 15 Sep 2016
A =[ 8 1 6
3 5 7
4 9 2];
n = 2;
s = size(A);
B = real(exp(conv2(log(A),ones(1,n),'valid')));
C = real(exp(conv2(log(A),ones(n,1),'valid')));
[b,bm] = max(B(:));
[c,cm] = max(C(:));
if b > c
[ii,jb] = ind2sub([s(1),s(2) - n + 1],bm);
out = {ii,jb + (0:n-1)};
else
[ic,jj] = ind2sub([s(1) - n + 1,s(2)],cm);
out = {ic + (0:n-1),jj};
end

Catégories

En savoir plus sur Operating on Diagonal Matrices 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