how can i make this code to run faster using vectorization?
Show older comments
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 Comments
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)
aslan shaghal
on 14 Sep 2018
Edited: aslan shaghal
on 14 Sep 2018
Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!