Loop through matrix to do calculations under conditions

Hello,
I'm a beginner with Matlab and I'd like to do some calculations for image processing.
Here is the deal :
I possess 2 matrices (B and C), which actually consist of 2 different images (M x N pixels). Each parameter of each matrix corresponds to the pixel information. I read the images with Imread, so it seems to me that the vectors are already indexed somewhat in Matlab.
I'd like to do the following calculation :
If abs( B-C ) > k/2; with k some coefficient (let's say 5, it doesn't matter, a number actually).
Do A = B - k. sign(B-C);
Else A = B;
By that I mean " if the difference B-C is more than half k, adding or substracting one k to B, depending on the sign of the difference. And thus, create A. "
I thought about some loop through the matrix to do the calculation, but all I can find so far on the internet is loops to replace the value of the matrix, and not to calculate under some conditions.
Waiting for some help, please tell me if you need more informations.
Thank you
Clément

2 comentarios

James Tursa
James Tursa el 18 de Mayo de 2016
Editada: James Tursa el 18 de Mayo de 2016
Did you mean abs(B-C) > k/2? If you don't use the abs, then it seems to me that the sign(B-C) will always be the same, and then the "adding or subtracting" part doesn't make sense to me. Please clarify.
Lulu
Lulu el 18 de Mayo de 2016
Editada: Lulu el 18 de Mayo de 2016
Yes abs(B-C)> k/2 of course. My bad.
What it means is : if B > C, thus A = B - k (substracting)
and if B < C, thus A = B + k (or adding)

Iniciar sesión para comentar.

 Respuesta aceptada

E.g., using a loop:
A = B;
for m=1:numel(A)
d = B(m) - C(m);
if( d > k/2 )
A(m) = A(m) - k;
elseif( d < -k/2 )
A(m) = A(m) + k;
end
end
A vectorized approach:
A = B;
D = B - C;
x = D > k/2;
A(x) = A(x) - k;
x = D < -k/2;
A(x) = A(x) + k;

Más respuestas (0)

Preguntada:

el 18 de Mayo de 2016

Comentada:

el 19 de Mayo de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by