Duke Glacia
Duke Glacia

Reputation: 85

How to efficiently implement the following code in MATLAB

M=50
G= randi(100,100,2);
N = 100;
iS = zeros(M,M);
for i1 = 1:M
  for i2 = 1:M
      if i1 == i2
          for g = 1:N
              iS(i1,i2) = iS(i1,i2) + eq(i1,G(g,1))+eq(i2,G(g,2));
          end
      else
          for g = 1:N
              iS(i1,i2) = iS(i1,i2)-(eq(i1,G(g,1))*eq(i2,G(g,2))+eq(i1,G(g,2))*eq(i2,G(g,1)));
          end
      end
          
  end 
end

I am trying to implement this code efficiently in MATLAB. The run time seems to take too much time. Is there a way to implement this code efficiently?

G is a 1000*2 double array.

Upvotes: 2

Views: 61

Answers (1)

rahnema1
rahnema1

Reputation: 15837

The loop can be reduced to the following vectorized form. Note that it uses matrix multiplication to speed up the calculation.

i1 = 1:M;
i2 = 1:M;
iS = -((i1 == G(:, 1)).' * (i2 == G(:, 2)) + (i1 == G(:, 2)).' * (i2 == G(:, 1)));
iS(1:M+1:end) = sum(i1 == G(:, 1)) + sum(i2 == G(:, 2));

For the last part you can also use histcounts:

i1 = 1:M;
i2 = 1:M;
iS = -((i1 == G(:, 1)).' * (i2 == G(:, 2)) + (i1 == G(:, 2)).' * (i2 == G(:, 1)));
iS(1:M+1:end) = histcounts(G(:, 1), 1:M+1) + histcounts(G(:, 2), 1:M+1);

Upvotes: 1

Related Questions