2

If I have :

for i=1:n
    for j=1:m
        if outputImg(i,j) < thresholdLow
            outputImg(i,j) = 0;
        elseif outputImg(i,j)> thresholdHigh
            outputImg(i,j) = 1;
        end
    end
end

or even worse :

for i=1:n
    for j=1:m
        for k=1:q
                % do something  
        end
    end
end

How can I achieve this differently , without for ?

1
  • The general answer to your question is "vectorize your code". Commented Jan 4, 2013 at 20:27

3 Answers 3

5

Instead of the first loop you can use logical conditions, such as:

 outputImg(outputImg<thresholdLow)=0;
 outputImg(outputImg>thresholdHigh)=1;

There are of course many other equivalent ways to get that using logical operators...

For the second loop you need to be more specific, but I think you got the grips of the logical conditions trick.

Sign up to request clarification or add additional context in comments.

Comments

1

For a general solution, look into ndgrid which in your second case you could use like this:

[i j k] = ndgrid(1:n, 1:m, 1:q);
ijk = [i(:) j(:) k(:)];

Then you can traverse the list of combinations of i, j, and k, i.e. now ijk to parameterize your thresholding statements.

3 Comments

Actually, no need to define ijk. You can simply use one for loop to go through the length of i which is the same as the length of k and of j to index these vectors. This is perhaps what @Leonid Beschastny meant by vectorizing your code.
How to write this dynamically? for example we want to write the [a1 a2 ... aN] = ndgrid(1:p); for variable N's. How to do this?
@MahdiKhosravi I think my answer is really not the best for the OP's question so perhaps you could post this as a separate one.
1

If you use binary matrix:

index_matrix = (outputImg < thresholdLow);

The following hold:

index_matrix(i,j) == 0 iff outputImg(i,j) < thresholdLow
index_matrix(i,j) == 1 iff outputImg(i,j) > thresholdLow

see also

for the second loop you can always use matirx over for loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.