2

For faster implementation , I would like to vectorize below matlab code :

 A=randi([0 1],20,20); B=zeros(20); for row = 5:15 for column = 5:15 if(A(row,column)==1 && (A(row+1,column)~=1 ||A(row,column+1)~=1)) B(row,column)=1; end end end 

How can I do that?

2 Answers 2

2

Just calculate all A(row, column)==1 and such at once for the whole loop, then use ordinary boolean operations. This should work just fine for the case you presented (though short-circuiting stuff operates a little bit differently, so this might not be always possible).

row = 5:15; col = 5:15; firstCond = A(row, col) == 1; secondCond = A(row+1, col) ~= 1; thirdCond = A(row, col+1) ~= 1; allCond = firstCond & (secondCond | thirdCond); B(row, col) = double(allCond); 
Sign up to request clarification or add additional context in comments.

1 Comment

voted up, but the this version of vectorization doesn't speed up much! ... average 3 mili sec :) ... a bit slower than amahmud 's version (see blow or up)...
1

I hope this one will work for you.

A=randi([0 1],20,20); B=zeros(20); z = find(A(5:15,5:15) == 1 & (A(6:16,5:15)~=1 | A(5:15,6:16)~=1)); y = B(5:15,5:15); y(z) = 1; B(5:15,5:15) = y; 

4 Comments

voted up and selected the answer, but your version of vectorization doesn't speed up much! ... average 3 mili sec :)
Now you are only using 20*20 matrix and the total time in the original case is around 0.003s which is really low. I think the speed up process will be much more visible for the large matrices.
I think @Zizy Archer's version is useful too if you just add all the logical expressions in one line. You can take a look at this too, A=randi([0 1],20,20); B=zeros(20); row = 5:15; col = 5:15; allCond = (A(row, col) == 1) &((A(row+1, col) ~= 1) | (A(row, col+1) ~= 1)); B(row, col) = double(allCond);
no, its not, I ran for 20000 times the average difference (between loop and zizy's version) is 0.0008.... btw, I tried substituting find directly into y() without using z... didn't become faster....

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.