How do I fill a column and/or row vector with the j-th/i-th sums of a magic matrix' vectors?

3 ビュー (過去 30 日間)
M W
M W 2018 年 3 月 2 日
編集済み: M W 2018 年 3 月 2 日
Hello :)
I'm trying to work through a simple for loop where I call a magic(4) matrix ("mag"), one "empty" column matrix of length "mag" and one "empty" row matrix of row length ("mag").
Objective: fill the i(th) and j(th) positions in the vectors with the sum of each i(row) and j(column). Below is the code that almost works:
mag = magic(4)
rows = zeros(length(mag),1)
columns = zeros(1,length(mag))
for i = mag(1:4,:)
rows(?) = sum(i);
end
for j = mag(:,1:4)
columns(?) = sum(j);
end
I have attempted several versions of, for example, "columns(:,j)", etc, but I can't seem to find the right combination to simply have rows(i)/columns(j) filled in sequence. When debugging the loop, I'd want to see this, for example: 1. [34 0 0 0] 2. [34 34 0 0] 3. [34 34 34 0] 4. [34 34 34 34] EXIT
It's probably something simple, so thanks.

回答 (1 件)

KL
KL 2018 年 3 月 2 日
編集済み: KL 2018 年 3 月 2 日
If I understand you correctly, you want to make the sum of rows and columns,
mag = rand(4);
r = sum(mag,1);
c = sum(mag,2);
or do you mean totally something else?
  1 件のコメント
M W
M W 2018 年 3 月 2 日
編集済み: M W 2018 年 3 月 2 日
I want to fill the positions in the declared column and row vectors sequentially, not all at once. The purpose is to check the stepped outcomes of a larger simulation, iteration by iteration, for debugging purposes.
I seem to have sorted part of it out:
mag = magic(4)
rows = zeros(length(mag),1)
columns = zeros(1,length(mag))
for i = 1:length(mag(:,1))
for j = 1:length(mag(1,:))
rows(i) = sum(mag(i,:));
columns(j) = sum(mag(:,j));
end
end
I am unsure if this could scale to a n.steps = 1000, N.simulations = 100 without becoming very slow.

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by