1

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.

Sjoerd C. de Vries
  • 65,815
  • 14
  • 188
  • 323
user92733
  • 11
  • 1
  • 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]... – rm -rf Oct 31 '13 at 02:25
  • @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;]";` – user92733 Oct 31 '13 at 03:55
  • @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]]. – Szabolcs Oct 31 '13 at 04:06
  • @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;]"; – user92733 Oct 31 '13 at 04:16
  • @user92733 That's just a transposition away from what MSet[..., matrixList] gives you, isn't it? – Szabolcs Oct 31 '13 at 05:10
  • @Szabolcs How to transpose? I've tried Transpose@matrixList and Transpose/@matrixList – user92733 Oct 31 '13 at 05:51
  • @user92733 In Mathematica, use the second argument of Transpose to achieve the proper permutation of the dimensions. Check the documentation for details please. In MATLAB the analogous function is called permute. Also note that while MATLAB prints m(:,:,1) and m(:,:,2), the matrices can be obtained by m(1,:,:) and m(2,:,:) without any transposition needed. – Szabolcs Oct 31 '13 at 15:39
  • @Szabolcs thanks, I hope this will speed up my codes. I seldom use the second argument of Transpose. – user92733 Nov 01 '13 at 11:54

0 Answers0