vectorization

2 次查看(过去 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

采纳的回答

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 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by