matlab conditioned matrix assignment

梦想的初衷 提交于 2019-12-04 03:51:24

问题


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.


回答1:


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;



回答2:


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;


来源:https://stackoverflow.com/questions/13132244/matlab-conditioned-matrix-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!