필터 지우기
필터 지우기

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 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