4

i have a question about matrix assignment.

say i have three matrices A, B and C, and i want to assign the elements of matrix C to the elements of A and B according to the rule

  C[i,j] = A[i,j] if abs(C[i,j] - A[i,j]) < abs(C[i,j] - B[i,j])
  C[i,j] = B[i,j] if abs(C[i,j] - A[i,j]) > abs(C[i,j] - B[i,j])
  C[i,j] = 0  if abs(C[i,j] - A[i,j]) == abs(C[i,j] - B[i,j])

how can i write it without for loops?

thanks very much for your help.

nos
  • 19,875
  • 27
  • 98
  • 134
  • 2
    You do realize that matrix indexing in MATLAB does not use [] ? I imagine that will cause you some problems once you ever use the language. –  Oct 30 '12 at 03:41

2 Answers2

5

I think Dan Becker has the right idea, but re-computing abs(C-B) and abs(C-A) implies that the updated matrices are compared, not the original ones.

I don't think this is what you want, so here's the corrected version of his method:

CmA = abs(C-A);
CmB = abs(C-B);

ind = Cma < CmB; C(ind) = A(ind);
ind = CmA > CmB; C(ind) = B(ind);
C(CmA == CmB) = 0;
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
  • Ah, nice catch - I agree that this is likely what the OP intended! I should perhaps not try to answer SO questions late at night ;-) – Dan Becker Oct 30 '12 at 14:38
1

I think that you want the following:

ind = abs(C - A) < abs(C - B) ; C(ind) = A(ind);
ind = abs(C - A) > abs(C - B) ; C(ind) = B(ind);
ind = abs(C - A) == abs(C - B) ; C(ind) = 0;
Dan Becker
  • 1,196
  • 10
  • 18