0

i want optimize some loop code such as below . my code is working with large matrix and must be optimized . please help me .

Example one: Expecting Boolean results:

m=zeros(100,100);
r=rand(100,100);
for i=1:100
    for j=1:100
        if(r(i,j)<0.3 || r(i,j)>0.7)
            m(i,j)=1;
        else
            m(i,j)=0;
        end
    end
end

Example two: Expecting NON-Boolean results

m=zeros(100,100);
r=rand(100,100);
for i=1:100
    for j=1:100
        if(r(i,j)<0.3 || r(i,j)>0.7)
            m(i,j)=0.035;
        else
            m(i,j)=0;
        end
    end
end

2 Answers 2

2

Vectorize:

m = r<0.3 | r>0.7;

This gives a boolean result. You may want to convert m to double: m = double(m);.

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

2 Comments

its good but if we wont boolean answer,what we must do? for example if m(i,j)=.035 insted of m(i,j)=1?
@RezaGhanami m * 0.035?
0

Example 1: Luis Mendo's answer

r=rand(100,100);
m = r<0.3 | r>0.7;

Example 2:

m(100,100) = 0;
r=rand(100,100);
m(r<0.3 | r>0.7) = 0.035;

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.