vectorization

조회 수: 3 (최근 30일)
Steven
Steven 2011년 12월 8일
hi,
is there a quick way to change the values of the diagonal of a matrix, instead of
for i = 1:length(A)
A(i,i) = 0;
end
thx
  댓글 수: 1
Andrei Bobrov
Andrei Bobrov 2011년 12월 8일
A-diag(diag(A))

댓글을 달려면 로그인하십시오.

채택된 답변

Dr. Seis
Dr. Seis 2011년 12월 8일
If A is an NxN matrix:
A(1:N+1:N*N) = 0;
  댓글 수: 1
Dr. Seis
Dr. Seis 2011년 12월 8일
N = 10000;
A = rand(N);
tic
A(1:N+1:N*N)=0;
toc % Took 0.000532 seconds
A = rand(N);
tic
A(logical(speye(length(A)))) = 0;
toc % Took 0.001379 seconds
A = rand(N);
tic
A = A - diag(diag(A));
toc % Took 0.215796 seconds

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Sean de Wolski
Sean de Wolski 2011년 12월 8일
One way:
A = magic(100); %sample matrix
A(logical(speye(length(A)))) = 0;
Also diag if you're building a matrix

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by