Scheduled service maintenance on November 22


On Friday, November 22, 2024, between 06:00 CET and 18:00 CET, GIN services will undergo planned maintenance. Extended service interruptions should be expected. We will try to keep downtimes to a minimum, but recommend that users avoid critical tasks, large data uploads, or DOI requests during this time.

We apologize for any inconvenience.

copymatrix.m 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. function m = copymatrix(varargin)
  2. % function m = copymatrix(m,sub,val)
  3. %
  4. % <m> is a matrix. can be [] when <sub> is a logical, in which case
  5. % we assume <m> is zeros(size(<sub>)).
  6. % <sub> is
  7. % (1) some sort of index (e.g. vector of indices, logical mask)
  8. % (2) a function that accepts <m> and outputs an index
  9. % <val> is something that can be assigned to the <sub> indices
  10. %
  11. % return a copy of <m> that has <val> shoved into <sub>.
  12. % this function is useful for making modifications of a matrix on-the-fly.
  13. %
  14. % example:
  15. % imagesc(copymatrix(randn(10,10),rand(10,10)>.5,0));
  16. % isequal(copymatrix([1 2 3],@(x) x > 1,1),[1 1 1])
  17. %
  18. % OR
  19. %
  20. % function m = copymatrix(m,sub,dim,val)
  21. %
  22. % <m> is a matrix
  23. % <sub> is a vector of indices or a vector of logicals
  24. % <dim> is a dimension of <m>
  25. % <val> is something that can be assigned to the <sub> indices of <m>,
  26. % assuming ':' for all other dimensions
  27. %
  28. % return a copy of <m> that has <val> shoved into <sub>.
  29. % this function is useful for making modifications of a matrix on-the-fly.
  30. %
  31. % example:
  32. % copymatrix([1 2 3; 4 5 6],2,1,[1 2 3])
  33. if nargin==3
  34. m = varargin{1};
  35. sub = varargin{2};
  36. val = varargin{3};
  37. if isa(sub,'logical') && isempty(m)
  38. m = zeros(size(sub));
  39. end
  40. if isa(sub,'function_handle')
  41. m(feval(sub,m)) = val;
  42. else
  43. m(sub) = val;
  44. end
  45. else
  46. m = varargin{1};
  47. sub = varargin{2};
  48. dim = varargin{3};
  49. val = varargin{4};
  50. ix = repmat({':'},[1 max(ndims(m),dim)]);
  51. ix{dim} = sub;
  52. m(ix{:}) = val;
  53. end