function m = copymatrix(m,sub,val) <m> is a matrix. can be [] when <sub> is a logical, in which case we assume <m> is zeros(size(<sub>)). <sub> is (1) some sort of index (e.g. vector of indices, logical mask) (2) a function that accepts <m> and outputs an index <val> is something that can be assigned to the <sub> indices return a copy of <m> that has <val> shoved into <sub>. this function is useful for making modifications of a matrix on-the-fly. example: imagesc(copymatrix(randn(10,10),rand(10,10)>.5,0)); isequal(copymatrix([1 2 3],@(x) x > 1,1),[1 1 1]) OR function m = copymatrix(m,sub,dim,val) <m> is a matrix <sub> is a vector of indices or a vector of logicals <dim> is a dimension of <m> <val> is something that can be assigned to the <sub> indices of <m>, assuming ':' for all other dimensions return a copy of <m> that has <val> shoved into <sub>. this function is useful for making modifications of a matrix on-the-fly. example: copymatrix([1 2 3; 4 5 6],2,1,[1 2 3])
0001 function m = copymatrix(varargin) 0002 0003 % function m = copymatrix(m,sub,val) 0004 % 0005 % <m> is a matrix. can be [] when <sub> is a logical, in which case 0006 % we assume <m> is zeros(size(<sub>)). 0007 % <sub> is 0008 % (1) some sort of index (e.g. vector of indices, logical mask) 0009 % (2) a function that accepts <m> and outputs an index 0010 % <val> is something that can be assigned to the <sub> indices 0011 % 0012 % return a copy of <m> that has <val> shoved into <sub>. 0013 % this function is useful for making modifications of a matrix on-the-fly. 0014 % 0015 % example: 0016 % imagesc(copymatrix(randn(10,10),rand(10,10)>.5,0)); 0017 % isequal(copymatrix([1 2 3],@(x) x > 1,1),[1 1 1]) 0018 % 0019 % OR 0020 % 0021 % function m = copymatrix(m,sub,dim,val) 0022 % 0023 % <m> is a matrix 0024 % <sub> is a vector of indices or a vector of logicals 0025 % <dim> is a dimension of <m> 0026 % <val> is something that can be assigned to the <sub> indices of <m>, 0027 % assuming ':' for all other dimensions 0028 % 0029 % return a copy of <m> that has <val> shoved into <sub>. 0030 % this function is useful for making modifications of a matrix on-the-fly. 0031 % 0032 % example: 0033 % copymatrix([1 2 3; 4 5 6],2,1,[1 2 3]) 0034 0035 if nargin==3 0036 m = varargin{1}; 0037 sub = varargin{2}; 0038 val = varargin{3}; 0039 if isa(sub,'logical') && isempty(m) 0040 m = zeros(size(sub)); 0041 end 0042 if isa(sub,'function_handle') 0043 m(feval(sub,m)) = val; 0044 else 0045 m(sub) = val; 0046 end 0047 else 0048 m = varargin{1}; 0049 sub = varargin{2}; 0050 dim = varargin{3}; 0051 val = varargin{4}; 0052 ix = repmat({':'},[1 max(ndims(m),dim)]); 0053 ix{dim} = sub; 0054 m(ix{:}) = val; 0055 end