how to create nxn matrix with main diagonal that enters odd rows/columns with zero and even ones start with 2(n+1) sequence

3 ビュー (過去 30 日間)
im trying to write a code where even main diagonal entries start off with 2 and continue 4,6,8.... etc but i only get outputs of 2. im assuming my problem is with the n=n+1 counter but im not sure.
my code is = for i=1:30;
For j=1:30;
for i=j
c=1;
if mod(i,2)~0 A(i,j)=2*c c=c+1; if mod (i, 2) ==0
A(i, j)=0;
end
end
end end
end

回答 (2 件)

Torsten
Torsten 2024 年 5 月 15 日
移動済み: Torsten 2024 年 5 月 15 日
n=10;
A=zeros(n);
for i=2:2:n
A(i,i) = i;
end
A
A = 10x10
0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

John D'Errico
John D'Errico 2024 年 5 月 15 日
Simple is to use diag.
n = 5; % Now many non-zero elements will we have?
N = 1:(2*n); % a simple index vector
D = N.*mod(N-1,2); % create the elements of the main diagonal
A = diag(D)
A = 10x10
0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by