placematrix.m 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. function m1 = placematrix(m1,m2,pos)
  2. % function m1 = placematrix(m1,m2,pos)
  3. %
  4. % <m1> is a 2D matrix, with potentially some extra stuff in the third dimension.
  5. % <m2> is a 2D matrix, with potentially some extra stuff in the third dimension.
  6. % note that size(m1,3) must equal size(m2,3).
  7. % <pos> (optional) is [R C] with a position. R and C can be any integers.
  8. % special case is [] which means to center <m2> with respect to <m1>.
  9. % if exact centering can't be achieved, we shift down and right.
  10. % default: [].
  11. %
  12. % place <m2> in <m1> positioned with first element at <pos>.
  13. % if any part of <m2> lies outside of <m1>, it just gets ignored.
  14. %
  15. % example:
  16. % isequal(placematrix([1 2 3; 4 5 6; 7 8 9],[10 10; 10 10],[0 0]),[10 2 3; 4 5 6; 7 8 9])
  17. %% SEE ALSO padarray.m ?
  18. %% see also assignsubvolume2.m???
  19. % input
  20. if ~exist('pos','var') || isempty(pos)
  21. pos = [];
  22. end
  23. m1r = size(m1,1);
  24. m1c = size(m1,2);
  25. m2r = size(m2,1);
  26. m2c = size(m2,2);
  27. if isempty(pos)
  28. pos = [1+ceil((m1r-m2r)/2) 1+ceil((m1c-m2c)/2)];
  29. end
  30. badup = max(0,1-pos(1)); % how many bad pixels to the up
  31. badleft = max(0,1-pos(2)); % how many bad pixels to the left
  32. baddown = max(0,(pos(1)+m2r-1)-m1r); % how many bad pixels to the bottom
  33. badright = max(0,(pos(2)+m2c-1)-m1c); % how many bad pixels to the right
  34. m1(pos(1)+badup:pos(1)+m2r-1-baddown,pos(2)+badleft:pos(2)+m2c-1-badright,:) = ...
  35. m2(1+badup:end-baddown,1+badleft:end-badright,:);