placematrix2.m 911 B

12345678910111213141516171819202122232425262728293031323334
  1. function m1 = placematrix2(m1,m2,pos)
  2. % function m1 = placematrix2(m1,m2,pos)
  3. %
  4. % <m1> is a matrix (cell matrix okay)
  5. % <m2> is a matrix (cell matrix okay)
  6. % <pos> (optional) is [x1 x2 x3 ...] with a position.
  7. % x1, x2, x3, etc. must be positive integers, and
  8. % there must be at least ndims(m2) of these numbers.
  9. % default is ones(1,ndims(m2)).
  10. %
  11. % place <m2> in <m1> positioned with first element at <pos>.
  12. % <m1> and <m2> must both be of the same type (matrix or cell matrix).
  13. % if <m1> is not large enough to accommodate <m2>, 0s or []s
  14. % are automatically filled in.
  15. %
  16. % example:
  17. % isequal(placematrix2([1 2 3; 4 5 6; 7 8 9],[0 0],[2 1]),[1 2 3; 0 0 6; 7 8 9])
  18. %% SEE ALSO padarray.m ?
  19. % input
  20. if ~exist('pos','var') || isempty(pos)
  21. pos = ones(1,ndims(m2));
  22. end
  23. % figure out indices
  24. indices = {};
  25. for p=1:length(pos)
  26. indices{p} = pos(p)-1 + (1:size(m2,p));
  27. end
  28. % do it
  29. m1(indices{:}) = m2;