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

James Tursa
James Tursa 2016년 5월 18일
편집: James Tursa 2016년 5월 18일
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 2016년 5월 18일
편집: Lulu 2016년 5월 18일
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)

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

 채택된 답변

James Tursa
James Tursa 2016년 5월 18일
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;

추가 답변 (0개)

질문:

2016년 5월 18일

댓글:

2016년 5월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by