vectorization

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 个评论

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

One way:
A = magic(100); %sample matrix
A(logical(speye(length(A)))) = 0;
Also diag if you're building a matrix

类别

在 帮助中心 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by