nos
nos

Reputation: 20880

matlab conditioned matrix assignment

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.

Upvotes: 4

Views: 147

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38042

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;

Upvotes: 5

Dan Becker
Dan Becker

Reputation: 1214

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;

Upvotes: 1

Related Questions