%SARR splits a 2D array into 3D adjacent subarrays
%
% SARR splits a 2D array into adjacent subarrays
% in COL -> ROW order.
% the subarrays are collected in a 3D array
% of size [SR,SC,SP], which facilitates
% block processing.
% the engine exclusively uses RESHAPE and PERMUTE
% to keep memory requirements low.
% SARR ends with an error if the size of the subarrays
% does not fit into the size of the array.
%
% see also: reshape, permute
%
%SYNTAX
%-------------------------------------------------------------------------------
% S = SARR(A, SRC)
% S = SARR(A,[SR,SC])
% S = SARR(A, SR,SC)
% [S,SS] = SARR(...)
%
%INPUT
%-------------------------------------------------------------------------------
% A : 2D array : any MATLAB data type
% Sx : subarray size :
% SR : number of rows
% SC : number of columns
% SRC : number of rows and columns
%
%OUTPUT
%-------------------------------------------------------------------------------
% S : 3D matrix with subarrays of size [SR,SC,SP]
% SS : full size of S
% SP : number of subarray pages
%
%EXAMPLE
%-------------------------------------------------------------------------------
% m=char(reshape(1:4*6,[4,6])+'@');
% s=sarr(m,3,4);
% disp(m);
% % AEIMQU
% % BFJNRV
% % CGKOSW
% % DHLPTX
% disp(s);
% % (:,:,1) = AEI % SP(1)
% % BFJ
% % (:,:,2) = CGK % SP(2)
% % DHL
% % (:,:,3) = MQU % SP(3)
% % NRV
% % (:,:,4) = OSW % SP(4)
% % PTX
% created:
% us 12-Jan-2002 us@neurol.unizh.ch
% modified:
% us 28-Jul-2009 12:05:43
%
% localid: us@USZ|ws-nos-36362|x86|Windows XP|7.8.0.347.R2009a
%-------------------------------------------------------------------------------
function [m,n]=sarr(m,sr,sc)
% input check
narg=nargin;
if narg < 2
help(mfilename);
if nargout
m=[];
n=0;
end
return;
end
% retrieve array/subarray size
[nr,nc]=size(m);
if narg == 2
if numel(sr) >= 2
sc=sr(2);
sr=sr(1);
else
sc=sr;
end
else
sr=sr(1);
end
% sanity check
if nr/sr ~= fix(nr/sr)
error('SARR> cannot split array [%d,%d] into %d rows',...
nr,nc,sr);
end
if nc/sc ~= fix(nc/sc)
error('SARR> cannot split array [%d,%d] into %d columns',...
nr,nc,sc);
end
% the engine
try
m=permute(reshape(m(:,reshape(1:nc,sc,nc/sc).'),sr,[],sc),[1,3,2]);
if nargout > 1
n=size(m);
end
catch %#ok
error('SARR> could not extract [%d/%d] subarrays from %s array [%d/%d]',...
sr,sc,class(m),nr,nc);
end
end
%-------------------------------------------------------------------------------