vectorization

3 vues (au cours des 30 derniers jours)
Steven
Steven le 8 Déc 2011
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 commentaire
Andrei Bobrov
Andrei Bobrov le 8 Déc 2011
A-diag(diag(A))

Connectez-vous pour commenter.

Réponse acceptée

Dr. Seis
Dr. Seis le 8 Déc 2011
If A is an NxN matrix:
A(1:N+1:N*N) = 0;
  1 commentaire
Dr. Seis
Dr. Seis le 8 Déc 2011
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

Connectez-vous pour commenter.

Plus de réponses (1)

Sean de Wolski
Sean de Wolski le 8 Déc 2011
One way:
A = magic(100); %sample matrix
A(logical(speye(length(A)))) = 0;
Also diag if you're building a matrix

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by