Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Pseudocode:

// B = nxn binary matrix
// Bm = resulting matrix
for (i=1; i<=n; i++)
{
  for (j=1; j<=n; j++)
  {
    if (B[i,j] == 1)
    {
      for (k=1; k<=n; k++)
      {
        Bm[i,j] = B[i,j] | B[k,j];
      }
    }
  }
}

This is the warshall algorithm written (in my way) in matlab:

B = [1 1 0 0 0; 0 0 0 1 0; 0 0 0 0 1; 0 1 0 0 0; 0 0 0 0 0];

n = 5;

Bm = zeros(n);

for i = 1:n
    for j = 1:n
        if B(i,j) == 1
            for k = 1:n
                Bm(i,k) = B(i,k) | B(k,j);
            end
        end
    end
end

It works but, how can I improve the matrix loops?

share|improve this question
    
Did you mean Bm(i,j) = B(i,k) | B(k,j)? –  Quentin Pradet May 7 '13 at 13:48

1 Answer 1

This post may help you in removing a loop: http://mathforum.org/kb/message.jspa?messageID=845980

Furthermore, one way to speed up your code is to use a short circuit logical operator:

B(i,k) || B(k,j); 

Also it seems to have a small effect if you use a logical matrix as input rather than a double:

B = logical(b);

Last and least, it would be nicer to initialize Bm with the datatype that it will have:

Bm = false(n)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.