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

2 views (last 30 days)
Lama on 15 May 2024
Answered: John D'Errico on 15 May 2024
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

Torsten on 15 May 2024
Moved: Torsten on 15 May 2024
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 on 15 May 2024
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>