function m1 = placematrix(m1,m2,pos) <m1> is a 2D matrix, with potentially some extra stuff in the third dimension. <m2> is a 2D matrix, with potentially some extra stuff in the third dimension. note that size(m1,3) must equal size(m2,3). <pos> (optional) is [R C] with a position. R and C can be any integers. special case is [] which means to center <m2> with respect to <m1>. if exact centering can't be achieved, we shift down and right. default: []. place <m2> in <m1> positioned with first element at <pos>. if any part of <m2> lies outside of <m1>, it just gets ignored. example: 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])
0001 function m1 = placematrix(m1,m2,pos) 0002 0003 % function m1 = placematrix(m1,m2,pos) 0004 % 0005 % <m1> is a 2D matrix, with potentially some extra stuff in the third dimension. 0006 % <m2> is a 2D matrix, with potentially some extra stuff in the third dimension. 0007 % note that size(m1,3) must equal size(m2,3). 0008 % <pos> (optional) is [R C] with a position. R and C can be any integers. 0009 % special case is [] which means to center <m2> with respect to <m1>. 0010 % if exact centering can't be achieved, we shift down and right. 0011 % default: []. 0012 % 0013 % place <m2> in <m1> positioned with first element at <pos>. 0014 % if any part of <m2> lies outside of <m1>, it just gets ignored. 0015 % 0016 % example: 0017 % 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]) 0018 0019 %% SEE ALSO padarray.m ? 0020 %% see also assignsubvolume2.m??? 0021 0022 % input 0023 if ~exist('pos','var') || isempty(pos) 0024 pos = []; 0025 end 0026 0027 m1r = size(m1,1); 0028 m1c = size(m1,2); 0029 m2r = size(m2,1); 0030 m2c = size(m2,2); 0031 0032 if isempty(pos) 0033 pos = [1+ceil((m1r-m2r)/2) 1+ceil((m1c-m2c)/2)]; 0034 end 0035 0036 badup = max(0,1-pos(1)); % how many bad pixels to the up 0037 badleft = max(0,1-pos(2)); % how many bad pixels to the left 0038 baddown = max(0,(pos(1)+m2r-1)-m1r); % how many bad pixels to the bottom 0039 badright = max(0,(pos(2)+m2c-1)-m1c); % how many bad pixels to the right 0040 0041 m1(pos(1)+badup:pos(1)+m2r-1-baddown,pos(2)+badleft:pos(2)+m2c-1-badright,:) = ... 0042 m2(1+badup:end-baddown,1+badleft:end-badright,:);