Filter löschen
Filter löschen

Vectorization of for loop

2 Ansichten (letzte 30 Tage)
Yaser Alghawi
Yaser Alghawi am 14 Mär. 2019
Kommentiert: Stephen23 am 14 Mär. 2019
I have this for loop with conditionals inside it.
for i=1:m
for j=1:n
if (flipped_im(i,j,1)>flipped_im(i,j,2)) || (flipped_im(i,j,1)>flipped_im(i,j,3))
mod_im(i,j,:)=255;
else
mod_im(i,j,:)=flipped_im(i,j,:);
end
end
end
How I can turn this loop into vectorized code?
  2 Kommentare
Stephen23
Stephen23 am 14 Mär. 2019
"How I can turn this loop into vectorized code?"
Why do you need to do that?
Yaser Alghawi
Yaser Alghawi am 14 Mär. 2019
It is an assignment. To optimize the speed of the program.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 14 Mär. 2019
Bearbeitet: Stephen23 am 14 Mär. 2019
In three lines, no loop:
>> new_im = flipped_im;
>> idx = new_im(:,:,1)>new_im(:,:,2) | new_im(:,:,1)>new_im(:,:,3);
>> new_im(idx(:,:,[1,1,1])) = 255;
and checking:
>> isequal(mod_im,new_im)
ans = 1
For MATLAB versions R2016b and later you can simplify the index code:
idx = any(new_im(:,:,1)>new_im(:,:,2:3),3);
  1 Kommentar
Jan
Jan am 14 Mär. 2019
Or in < R2016b:
idx = any(new_im(:,:, [1, 1]) > new_im(:,:, 2:3), 3);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Yaser Alghawi
Yaser Alghawi am 14 Mär. 2019
Thank you Chris and Jan. It did the trick.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by