Vectorisation for nested for loops in Piecewise Linear Transformation

Hi everyone,
I'm trying to remove the for loops in this piecewise linear transformation function and have tried using vectorisation but can't wrap my head around how the code would look.
for i = 1:size(original,1)
for j = 1:size(original,2)
if (original(i,j) < x1)
transformed(i,j) = m1 * original(i,j);
elseif (original(i,j) >= x1 && original(i,j) < x2)
transformed(i,j) = m2 * (original(i,j) - x1) + y1;
else
transformed(i,j) = m3 * (original(i,j) - x2) + y2;
end
end
end
Is there any way I can do a piecewise linear transformation (contrast stretching) without the nested for loop to speed up the execution?

 採用された回答

Voss
Voss 2022 年 11 月 10 日
transformed = original;
idx = original < x1;
transformed(idx) = m1 * original(idx);
idx = original >= x1 & original < x2;
transformed(idx) = m2 * (original(idx) - x1) + y1;
idx = original >= x2;
transformed(idx) = m3 * (original(idx) - x2) + y2;

1 件のコメント

Sophia
Sophia 2022 年 11 月 10 日
Thank you so much! It makes a lot of sense now :)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

質問済み:

2022 年 11 月 10 日

コメント済み:

2022 年 11 月 10 日

Community Treasure Hunt

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

Start Hunting!

Translated by