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

Stephen23
Stephen23 2019년 3월 14일
"How I can turn this loop into vectorized code?"
Why do you need to do that?
Yaser Alghawi
Yaser Alghawi 2019년 3월 14일
It is an assignment. To optimize the speed of the program.

댓글을 달려면 로그인하십시오.

 채택된 답변

Stephen23
Stephen23 2019년 3월 14일
편집: Stephen23 2019년 3월 14일

1 개 추천

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

Jan
Jan 2019년 3월 14일
Or in < R2016b:
idx = any(new_im(:,:, [1, 1]) > new_im(:,:, 2:3), 3);

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Yaser Alghawi
Yaser Alghawi 2019년 3월 14일

0 개 추천

Thank you Chris and Jan. It did the trick.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2019년 3월 14일

댓글:

2019년 3월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by