Vectorization of nested for-loop and if-statements

I am trying to vectorize the next nested loop, so I don't need to build the values ​​in the loop:

for i=1:size(validMaskX,1) for j=1:size(validMaskX,2) if( validMaskX(i,j) ) plot(ah, [dataX(i,j) dataX(i,j+1)], [dataY(i,j) dataY(i,j+1)], 'g-') end end end 
  • size (validMaskX) = 45x44
  • size (DataX) = size (dataY) = 45x45

Any suggestions on how to do this?

+5
source share
3 answers

WITH

 vind=find(validMaskX); vindn = vind + size(validMaskX, 1); 

You can find valid points and other indices. Then you can build with

 plot(ah, [dataX(vind), dataX(vindn)], [dataY(vind), dataY(vindn)], 'g-'); 

If you need only one plot object (to make rendering much faster), consider

 dx = [dataX(vind), dataX(vindn), nan(numel(vind), 1)]'; dy = [dataY(vind), dataY(vindn), nan(numel(vind), 1)]'; plot(ah, dx(:), dy(:), 'g-'); 
+2
source

If you want all the lines to be together in the picture, you can do this:

 ind=find(validMask); X=[dataX(ind) dataX(ind+45) nan(length(ind),1)]; Y=[dataY(ind) dataY(ind+45) nan(length(ind),1)]; plot(ah,X',Y','g-') 
+1
source

I thought I understood your decision yesterday, but apparently I do not, because when I try to change the following code according to your answer, it does not work: how would you change this according to your previous answer?

 for i=1:size(validMaskY,1) for j=1:size(validMaskY,2) if( validMaskY(i,j) ) plot(ah, [dataX(i,j) dataX(i+1,j)], [dataY(i,j) dataY(i+1,j)], 'r-') end end end 

size (DataX) = size (dataY)

0
source

Source: https://habr.com/ru/post/1237243/


All Articles