How do I create every sum of column entries of a m x n matrix?

5 ビュー (過去 30 日間)
Viktor von den Brincken
Viktor von den Brincken 2017 年 12 月 19 日
回答済み: Viktor von den Brincken 2017 年 12 月 27 日
I would like to create the sums of a mxn matrix that have m summands, one of each row - using a for loop to generate every possible combination. For my 3x3 Matrix A my code would look like this:
for i=1:3
for j=1:3
for k=1:3
S=A(1,i)+A(2,j)+A(3,k);
end
end
end
Now I need this to work for any mxn Matrix. How? Do I need a recursive function or is there any other way?

採用された回答

Viktor von den Brincken
Viktor von den Brincken 2017 年 12 月 27 日
Figured another way:
close
clear
clc
A = [1 2 3; 4 5 6;7 8 9];
[Zeile,Spalte] = size(A);
S=MatAdd(A,1);
with
function [Summe] = MatAdd(A,aktuelleZeile)
Summe=[];
[AnzahlZeilen,AnzahlSpalten] = size(A);
if aktuelleZeile==AnzahlZeilen
Summe=A(aktuelleZeile,:)';
else
Summanden=MatAdd(A,aktuelleZeile+1);
for i=1:AnzahlSpalten
Summe=[Summe;Summanden+A(aktuelleZeile,i);];
end
end
end

その他の回答 (2 件)

Jos (10584)
Jos (10584) 2017 年 12 月 19 日
read the help of sum, and take a look at the dimension argument
help sum
M = randi(10,3,4)
sum(M,1) % sum along rows
  2 件のコメント
Viktor von den Brincken
Viktor von den Brincken 2017 年 12 月 19 日
編集済み: Viktor von den Brincken 2017 年 12 月 19 日
this way I get max 3 Sums of my expected 27 for the 3x3 matrix.
Jos (10584)
Jos (10584) 2017 年 12 月 19 日
O, sorry, I misunderstood your question. So you have n-columns, each with m values (hence the the m-by-n matrix) and you want the sum of the m^n possible combinations ...

サインインしてコメントする。


Jos (10584)
Jos (10584) 2017 年 12 月 19 日
A = magic(3)
[m,n] = size(A)
% get the row indices into A for every combination
clear r
[r{n:-1:1}] = ndgrid(1:m)
r = reshape(cat(n+1,r{:}),[],n)
% or use PERMN from the file exchange
% get the columns indices
c = repmat(1:n,size(r,1),1) ;
% transform into linear indices
idx = sub2ind([m,n],r,c) ;
% get the summands for each combination
B = A(idx)
% and sum
out = sum(B,2)
  1 件のコメント
Viktor von den Brincken
Viktor von den Brincken 2017 年 12 月 19 日
this looks promising. I'll look into it and try to understand. Thank you very much!!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by