%mathpiper,title="ExtractSubMatrix"

//Retract("ExtractSubMatrix",*);

10 # ExtractSubMatrix( mat_IsMatrix, _row1, _col1, _row2, _col2 )_
       (And(IsPositiveInteger(row1),IsPositiveInteger(col1),
            IsPositiveInteger(row2),IsPositiveInteger(col2))) <--
[
    Local(nrows,ncols,r,row,result);
    {nrows,ncols} := Dimensions( mat );
    Check(And(row1>0,col1>0,row1<nrows,col1<ncols), "Math", "ERROR: UL out of range");
    Check(And(row2>row1,col2>col1,row2<=nrows,col2<=ncols), "Math", "ERROR: LR out of range");
    result := {};
    For(r:=row1,r<=row2,r++)
    [
        row := Take( MatrixRow(mat,r), {col1,col2} );
        result := DestructiveAppend( result, row );
    ];
    result;
];


10 # ExtractSubMatrix( mat_IsMatrix, _row1, _col1 )_
              (And(IsPositiveInteger(row1),IsPositiveInteger(col1))) <--
[
    Local(nrows,ncols);
    {nrows,ncols} := Dimensions( mat );
    Check(And(row1>0,col1>0,row1<nrows,col1<ncols), "Math", "ERROR: UL out of range");
    ExtractSubMatrix( mat, row1, col1, nrows, ncols );
];

%/mathpiper






%mathpiper_docs,name="ExtractSubMatrix",categories="User Functions;Linear Algebra"
*CMD ExtractSubMatrix --- Extract a submatrix from a given matrix
*STD
*CALL
	ExtractSubMatrix(matrix,row1,col1,row2,col2)

*PARMS
{matrix} -- matrix from which to extract a submatrix
{row1,col1} -- UpperLeft  (UL) corner of submatrix
{row2,col2} -- LowerRight (LR) corner of submatrix

*DESC
Given a  {matrix}  with {nr} rows and {nc} columns, not necessarily square,
this command extracts and return the specified submatrix.  
If {row2,col2} are omitted, they default to {nr,nc}.
The original matrix is left unchanged.
The inputs are checked for sanity.

*E.G. notest
In> AM := {{11,12,13,14},{21,22,23,24},{31,32,33,34}}
Result: {{11,12,13,14},{21,22,23,24},{31,32,33,34}}

In> ExtractSubMatrix(AM,2,2,3,3)
Result: {{22,23},{32,33}}

In> ExtractSubMatrix(AM,2,2);
Result: {{22,23,24},{32,33,34}}

In> ExtractSubMatrix(AM,0,2,1,3);
Result: ExtractSubMatrix({{11,12,13,14},{21,22,23,24},{31,32,33,34}},0,2,1,3)

In> ExtractSubMatrix(AM,1,3,2,5)
Result: 
Exception: ERROR: LR out of range

%/mathpiper_docs

    %output,preserve="false"
      
.   %/output


