Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the value of a multidimensional array with the output as compatible matlab code

For matrices with dimensions equal or less then 2 the command is:

For instance:

>> mat2str(ones(2,2))

ans =

[1 1;1 1]

However, as the help states, this does not work for higher dimensions:

>> mat2str(rand(2,2,2))
Error using mat2str (line 49)
Input matrix must be 2-D.

How to output matrices with higher dimensions than 2 with that is code compatible, without resorting to custom made for loops?

like image 590
hakanc Avatar asked Dec 11 '25 03:12

hakanc


1 Answers

This isn't directly possible because there is no built-in character to represent concatenation in the third dimension (an analog to the comma and semicolon in 2D). One potential workaround for this would be to perform mat2str on all "slices" in the third dimension and wrap them in a call to cat which, when executed, would concatenate all of the 2D matrices in the third dimension to recreate your input matrix.

M = reshape(1:8, [2 2 2]);

arrays = arrayfun(@(k)mat2str(M(:,:,k)), 1:size(M, 3), 'uni', 0);
result = ['cat(3', sprintf(', %s', arrays{:}), ')'];

result =

    'cat(3, [1 3;2 4], [5 7;6 8])'

isequal(eval(result), M)

    1

UPDATE

After thinking about this some more, a more elegant solution is to flatten the input matrix, run mat2str on that, and then in the string used to recreate the data, we utilize reshape combined with the original dimensions to provide a command which will recreate the data. This will work for any dimension of data.

result = sprintf('reshape(%s, %s);', mat2str(M(:)), mat2str(size(M)));

So for the following 4D input

M = randi([0 9], 1, 2, 3, 4);
result = sprintf('reshape(%s, %s);', mat2str(M(:)), mat2str(size(M)));

    'reshape([6;9;4;6;5;2;6;1;7;2;1;7;2;1;6;2;2;8;3;1;1;3;8;5], [1 2 3 4]);'

Now if we reconstruct the data using this generated string, we can ensure that we get the correct data back.

Mnew = eval(result);
size(Mnew)

    1   2   3   4

isequal(Mnew, M)

    1

By specifying both the class and precision inputs to mat2str, we can even better approximate the input data including floating point numbers.

M = rand(1,2,3,4,5);
result = sprintf('reshape(%s, %s);', mat2str(M(:),64,'class'), mat2str(size(M)));

isequal(eval(result), M)

    1
like image 189
Suever Avatar answered Dec 13 '25 22:12

Suever