How to calculate and store the sum of different column combinations in a matrix?
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Monire Jalili
am 30 Jan. 2020
Beantwortet: edward holt
am 31 Jan. 2020
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.
0 Kommentare
Akzeptierte Antwort
edward holt
am 31 Jan. 2020
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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!