Reaching Matlab `num2str` behavior in Octave

Following code

x = [1.1, 2.22, -3.3; 4.44, 5.55, 6.6]; fmt = '%.16g '; y = num2str(x, fmt) 

gives different results in Matlab (R20105b)

 y = 1.1 2.22 -3.3 4.44 5.55 6.6 

and in Octave (4.0.0)

 y = 1.1 2.22 -3.3 4.44 5.55 6.6 

The difference is alignment : in Matlab, the columns are right-aligned, while in Octave, they are not aligned.

I would like to achieve the exact Matlab behavior in Octave. Do you know any solution for this? Of course, I could write my own function, but maybe a solution already exists.

EDIT

Another difference is how multidimensional arrays are handled. For example,

 x = cat(3, magic(3), -magic(3)); fmt = '%.16g '; y = num2str(x, fmt) 

produces in matlab

 y = 8 1 6 -8 -1 -6 3 5 7 -3 -5 -7 4 9 2 -4 -9 -2 

and in octave

 y = 8 1 6 3 5 7 4 9 2 -8 -1 -6 -3 -5 -7 -4 -9 -2 

That is, Matlab joins 3D fragments along the second dimension, and Octave - along the first.

+7
string printf matlab octave
source share
1 answer

This is more a workaround than a solution; and I'm not quite happy with that. But here everything goes. If anyone has a better or more general solution, please let me know.

The following only works for one formatting operator, as in the example (it does not work for something like fmt = '%.2f %.1f' ), and only for real (not complicated) numbers. It works for arrays with sizes larger than 2 , simulating the behavior of Matlab: it collapses all dimensions beyond the first into one (second) dimension.

 if ischar(x) y = x; else y = sprintf([fmt '\n'], reshape(x,size(x,1),[]).'); %'// each row of y is a string. % // '\n' is used as separator y = regexp(y, '\n', 'split'); %// separate y = y(1:end-1).'; %'// remove last '\n' y = cellfun(@fliplr, y, 'uniformoutput', false); %// invert each string y = char(y); %// concatenate the strings vertically. This aligns to the left y = fliplr(y); %// invert back to get right alignment y = reshape(y.',[],size(x,1)).'; %// reshape into the shape of x y = strtrim(y); %// remove leading and trailing space, like num2str does end 

This gives, as in Matlab in Octave, the same result as expressed y = num2str(x, fmt) in Matlab.

It should be noted that when the first input is a char num2str , it ignores the second input (format specifier) ​​and produces the same char array as output, both in Matlab and in Octave. So num2str('abc', '%f ') produces 'abc' . However, sprintf works in different ways: it forces the use of a format specifier, interpreting input characters as ASCII codes, if necessary. Therefore, the if branch is required in the above code.

+2
source share

All Articles