how can i make this code to run faster using vectorization?

I have an adjacency matrix(A) of 0 and 1 elements. for each of the elements in the matrix that is equal to 1, I have to replace it with 0. then exponentiate the matrix until that element will become a none zero element. so I have written this code here, the problem is it's very slow and I have no idea how to improve that. I would appreciate it if anyone could help me. A=[0 1 1 1 0; 1 0 1 0 1; 1 1 0 1 1; 1 0 1 0 0; 0 1 1 0 0]
clc;
clear;
adjacency=load ('sample');
A=adjacency.A;
n=size(A,1);
An=A;
b=zeros(n,n);
for i=1:n
for j=i+1:n %because the matrix is symmetric I do this to get rid of extra calculation
if A(i,j)==1
A(i,j)=0;
An(i,j)=0;
while An(i,j)==0
An=An*A;
end
b(i,j)=An(i,j);
A(i,j)=1; % this line is for changing the A to the original matrix
An=A; % this line is for changing the An to the original matrix
else
b(i,j)=0;
end
b(j,i)=b(i,j);
end
end

2 个评论

The load() function is probably what's slowing your code down, not the loops. I replaced the first 4 lines of your code with
A=[0 1 1 1 0; 1 0 1 0 1; 1 1 0 1 1;1 0 1 0 0; 0 1 1 0 0];
and ran it 10,000 times which only took 0.063 seconds (using tic/toc). The mean run time was 0.0000063 seconds with a standard deviation of 0.000017. That's pretty fast. (using matlab 2018b)
I should mention that the actual A is much larger than this and it could be up to 2000 by 2000; after profiling the code, the part that slows down the code is:
An=An*A
I try to replace this part with
An=A^t;
t=t+1;
and preallocate t=1, but the result is not desirable.

请先登录,再进行评论。

回答(0 个)

类别

帮助中心File 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