(*                MatlabInterface



           Techno-Sciences, Inc.
           10001 Derekwood Lane, Suite 204
           Lanham, MD 20706
           (301) 577-6000
           
           
Copyright © 1997, 1998 Techno-Sciences Incorporated
All Rights Reserved          
           
*)
spell1 = (Head[General::spell1] === $Off);
spell = (Head[General::spell] === $Off);
Off[General::spell1];
Off[General::spell]; 



BeginPackage["ProPac`MatlabInterface`",{"DiscreteMath`Combinatorica`"}]

(* ********************************************************************** *)
(* ********************************************************************** *)


(* Function Usage Statements *)

MatlabInterface::usage=
"The basic tools in MatlabInterface are:\n
\n
MatlabForm\n
\n
and
\n
MatlabFormPolynomials\n
"


MatlabForm::usage = 
"MatlabForm[Matrix,MatrixName] converts the matrix or vector expression given 
by the first argument Matrix into a Matlab readable and executable string with a
variable name given by the second argument MatrixName. For example,

x_matlabform = MatlabForm[{{1,2},{3,4}},x] 
returns a string of the form 

xmatlabform = x=[1,2;3,4];

This function is useful for transfering matrices from Mathematica to Matlab via an ASCII
file. The process is as follows: 

  (1) Using the above function, convert the pertinent matrices to 
      Matlab readable strings.
  (2) Write the strings to an ASCII file.
  (3) At the Matlab prompt, type the name of the file which will execute the matrix assignments."

MatlabFormPolynomials::usage=
"MatlabFormPolynomials[Polynomial,order,name,Filename] creates a\n
Malab readable file 'Filename.m' that defines the matrix coefficients\n
of matrix-valued multivariate polynomials in the list 'Polynomial'.\n
Coefficients up to degree 'order' are generated. 'name' is a list of\n
base names (strings) for the coefficents.\n

Example:\n
A = {x^2 + x y + 2 y^2, 2 + x}, {3, x + 3 x^2 + y + x y}}\n
Polynomial={A};\n
order=3;\n
names={ToString[A]};\n
Filename=ToString[TestFile.m];\n
MatlabFormPolynomials[Polynomial,order,names,Filename]\n
\n
Produces an ASCII file named TestFile.m containing:\n 
\n
'Variables=[x,y]'\n
A00=[0,2;3,0];\n
A01=[0,0;0,1];\n
A10=[0,1;0,1];\n
A02=[2,0;0,0];\n
A11=[1,0;0,1];\n
A20=[1,0;0,3];\n
A03=[0,0;0,0];\n
A12=[0,0;0,0];\n
A21=[0,0;0,0];\n
A30=[0,0;0,0];\n
\n
At the Matlab prompt, type the name of the file and press enter\n
to execute the matrix assignments.\n
\n
Matrices of the form Aij are coefficents of terms of the form x^i*y^j\n
\n
The reconstructed polynomial is\n
A00+A01y+A10x+A02y^2+A11xy+A20x^2+A03y^3+A12xy^2+A21x^2y^2+A30x^3
"


Begin["`private`"]

Clear[MatlabForm]
MatlabForm[Matrix_,Matrixname_]:=Module[{MatrixRules,VectorRules,M2},(
    MatrixRules={"{{"->"[","}}"->"]","}, {"->";", ", "->","};
    VectorRules={"{"->"[","}"->"]", ", "->","};
    If[MatrixQ[Matrix],
      {n,m}=Dimensions[Matrix];
      M2 = StringReplace[ToString[NumberForm[Matrix,16,ExponentFunction -> (If[-100 < # < 100, Null,#]&)]],MatrixRules],
      M2 = StringReplace[ToString[NumberForm[Matrix,16,ExponentFunction -> (If[-100 < # < 100, Null,#]&)]],VectorRules]
    ];
    StringJoin[Matrixname,"=",M2,";"]
)];
SetAttribute[MatlabForm,ReadProtected];
SetAttribute[MatlabForm,Protected];
SetAttribute[MatlabForm,Locked];

IndexList[0,kk_]:=Compositions[0,kk]
IndexList[jj_,kk_]:=Join[IndexList[jj-1,kk],Compositions[jj,kk]]

PolyTerm[Index_List,Param_List]:=Inner[Power,Param,Index,Times]

WriteCoefficient[Mat_,name_,channel_]:=Module[{rhs},
	      rhs=MatlabForm[Mat,name];
			WriteString[channel,rhs<>"\n"]
				]

CreateString[A_String,{}]:=A
CreateString[A_String,B_?VectorQ]:=
  CreateString[A<>ToString[B[[1]]],Drop[B,1]]

WritePolyomialCoefficients[Polynomial_?MatrixQ,name_String,Variable_List,
    Index_List,Terms_List,channel_]:=Module[{coefnames,coeflist},
		coefnames=Map[CreateString[name,#]&,Index];
		coeflist=
      Map[(Coefficient[Polynomial,#]/.Inner[Rule,Variable,
                Table[0,{Length[Variable]}],List])&,Drop[Terms,1]];
		coeflist=
      Join[{Polynomial/.Inner[Rule,Variable,Table[0,{Length[Variable]}],
              List]},coeflist];
		MapThread[WriteCoefficient[#1,#2,channel]&,{coeflist,coefnames}]
		]
WritePolyomialCoefficients[Polynomial_List,name_List,Variable_List,Index_List,
    Terms_List,channel_]:=Module[{},
		WritePolyomialCoefficients[Polynomial[[1]],name[[1]],Variable,Index,Terms,
        channel];
		WritePolyomialCoefficients[Drop[Polynomial,1],Drop[name,1],Variable,Index,
        Terms,channel]
		]/;Polynomial!={}
      
Clear[MatlabFormPolynomials]      
MatlabFormPolynomials[Polynomial_List,order_Integer,name_List,
    Filename_String]:=Module[{Index,Terms,channel,Variable},
		Variable=Variables[Polynomial];
		Index=IndexList[order,Length[Variable]];
		Terms=Map[PolyTerm[#,Variable]&,Index];
      channel=OpenWrite[Filename];
      WriteString[channel,StringDrop[MatlabForm[Variable,"'Variables"],-1]<>"'\n"];		
      WritePolyomialCoefficients[Polynomial,name,Variable,Index,Terms,channel];
		Close[channel]
   ]
SetAttribute[MatlabFormPolynomials,ReadProtected];
SetAttribute[MatlabFormPolynomials,Protected];
SetAttribute[MMatlabFormPolynomials,Locked];





(* ********************************************************************** *)
(* ********************************************************************** *)

(* ********************************************************************** *)
(* ********************************************************************** *)


Print["  *** MatlabInterface successfully loaded ***"];

End[]
EndPackage[ ]

(* ********************************************************************** *)
(* ********************************************************************** *)
If[!spell1, On[General::spell1]];
If[!spell, On[General::spell]];

