How to calculate and store the sum of different column combinations in a matrix?

조회 수: 3 (최근 30일)
We have a matrix a(i,j) with i:1:M and j:1:N
We want to calculate the sum of all column combinations of N elements each from a distinct column and store them in a new array/matrix. This new matrix/array will have M^N elements. We need to also store which combination yeild this sum.
suppose M=3 and N=4
a = [1,2,3,4;5,6,7,8;9,10,11,12]
a(1,1)+a(1,2)+a(1,3)+a(1,4)--> sum of first element of every column
a(1,1)+a(2,2)+a(1,3)+a(1,4)--> sum of first element of column 1, 3 and 4 and 2nd element of column 2
a(1,1)+a(3,2)+a(1,3)+a(1,4)--> sum of first element of column 1, 3 and 4 and 3rd element of column 2
.
There will be 3^4 combinations.
The goal is to find out which sum combination yields the maximum and be able to report the location of elements of that combination in the main matrix a.

채택된 답변

edward holt
edward holt 2020년 1월 31일
A similar question has been asked here.
Finding out which combination yields the maximum can be done without summing all possible combinations.
m = 5
n = 4
a = randi(10,m,n)
[coltots, where] = max(a);
tot = sum(coltots)
%gives maximum value
where
%and which rows it came form
For summing and organising all possible pairs
combos = zeros(m,m,m,m);
% will be an N dimensional array, with lengths M
% need N many loops
for i1 = 1:m
for i2 = 1:m
for i3 = 1:m
for i4 = 1:m
combos(i1,i2,i3,i4) = a(i1,1) + a(i2,2) + a(i3,3) + a(i4,4);
end
end
end
end
combos == tot
I'm sure there is a better way, that's beyond my skillset. It's a nice problem to think on.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by