1
$\begingroup$

How can I convert a matrix into matlab form?

matrix2Matlab[matrix0_] :=  Module[{matrix = matrix0},   "[" <> StringReplace[    ExportString[matrix, "CSV"], {"\n" -> ";", "," -> " "}] <> "]"]

matrix2Matlab[m = IdentityMatrix[3]]

(*
    [1 0 0;0 1 0;0 0 1]
*)

Are there more simpler ways?

I use MATLink to deal with the string matrix.

$\endgroup$
8
  • $\begingroup$ You need the ToMatlab package... See my answer in the linked question for details on obtaining the package and using it. For your case, all you need to do is ToMatlab@IdentityMatrix@3. However, if you're using MATLink, you don't need to do any of this... could you perhaps clarify your usage? You can transfer to MATLAB using MSet["mat", IdentityMatrix@3]... $\endgroup$
    – rm -rf
    Oct 31 '13 at 2:25
  • $\begingroup$ @rm-rf Hi, do you know how to MSet a matrixList like here what the MEvaluate do? matrixList={IdentityMatrix[3],Partition[Range[9],3]}; MATLinkMEvaluate@"m = [ 1 0 0; 0 1 0; 0 0 1]; m(:,:,2) = [1 2 3;4 5 6;7 8 9;]";` $\endgroup$
    – user92733
    Oct 31 '13 at 3:55
  • $\begingroup$ @user92733 What kind of data structure are you expecting on the MATLAB side? matrixList here is really a 3D array, so that's what you get with MSet["s", matrixList]. If you want to treat it as a list of two matrices, you can represent it as a cell which contains two 3x3 matrices and transfer it using MSet["c", MCell[matrixList]]. $\endgroup$
    – Szabolcs
    Oct 31 '13 at 4:06
  • $\begingroup$ @Szabolcs Hi, the expected result on the Matlab side is shown by MATLinkMEvaluate@"m = [ 1 0 0; 0 1 0; 0 0 1]; m(:,:,2) = [1 2 3;4 5 6;7 8 9;]"; $\endgroup$
    – user92733
    Oct 31 '13 at 4:16
  • $\begingroup$ @user92733 That's just a transposition away from what MSet[..., matrixList] gives you, isn't it? $\endgroup$
    – Szabolcs
    Oct 31 '13 at 5:10