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 次查看(过去 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 CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by