M.A. - 8 months ago 44

Java Question

I have a code in MATLAB that gives me a matrix at the end. I need to take this matrix to Java and use it there, but when the matrix is big, it is really hard to rewrite it element by element in Java. So I wrote this code in MATLAB:

`function JavaMatrix = generateJavaFormatedMatrix(matrix, name)`

for i=1:size(matrix,1)

for j=1:size(matrix,2)

JavaMatrix(i,j) = char([name '[' num2str(i-1) ']' '[' num2str(j-1) ']=' num2str(matrix(i,j)) ';' ' '])

end

end

end

Which I expect it to do the trick for me, and then I just need to copy the array and paste it in Java. For example, what I want the above code to do when I write the following command:

`java_matrix = generateJavaFormatedMatrix(eye(3),'A')`

is the following

`A[0][0]=1; A[0][1]=0; A[0][2]=0;`

A[1][0]=0; A[1][1]=1; A[1][2]=0;

A[2][0]=0; A[2][1]=0; A[2][2]=1;

However, what I am getting is the following error:

`Subscripted assignment dimension mismatch.`

Error in generateJavaFormatedMatrix (line 5)

JavaMatrix(i,j) = char([name '[' num2str(i-1) ']' '[' num2str(j-1) ']=' num2str(matrix(i,j)) ';' ' '])

Any help is highly appreciated.

Answer Source

Here is a code that does the trick.

```
function s = generateJavaFormatedMatrix( A, sigdigs, name )
if nargin < 2
sigdigs = 15;
end
format = [ '%+1.', int2str(sigdigs), 'e' ];
s = sprintf( 'final double [][] %s = {\n', name );
for row = 1:size(A,1)
s = [ s, ' { ' ];
for col = 1:size(A,2)
s = [ s, num2str( A(row,col), format ) ];
if ( col ~= size(A,2) )
s = [ s, ', ' ];
end
end
if row == size(A,1)
s = sprintf( [ s, ' } \n' ] );
else
s = sprintf( [ s, ' }, \n' ] );
end
end
s = [ s, '};' ];
```

So for example, running this command

```
>> generateJavaFormatedMatrix( eye(3), 3, 'A' ):
```

will give:

```
ans =
final double [][] A = {
{ +1.000e+00, +0.000e+00, +0.000e+00 },
{ +0.000e+00, +1.000e+00, +0.000e+00 },
{ +0.000e+00, +0.000e+00, +1.000e+00 }
};
```