I am new to Matlab. Is there a way to use printmat
to print 2 words heading?
Example result as followed:
Title One Title Two Title Three
11 22 33
22 33 44
Here is the code i currently trying to modify:
matA = [ 11 22 33; 22 33 44];
printmat(matA, '' , '' , 'TitleOne TitleTwo TitleThree');
I can't seems to add a space in between 'Title' and 'One' where adding the space always result in the following outcome:
printmat(matA, '' , '' , 'Title One Title Two Title Three');
Title One Title
11 22 33
22 33 44
Any help is appreciated.
According to Matlabs help, printmat
will not provide what you are seeking. You can use sprintf
instead.
a = [ 11 22 33; 22 33 44];
s = {'Title One' 'Title Two' 'Title Three'};
s1 = sprintf('%12s\t%12s\t%12s\t\n', s{:});
s2 = sprintf('%12d\t%12d\t%12d\n', a);
horzcat(s1,s2)
This results in
ans =
Title One Title Two Title Three
11 22 22
33 33 44
~edit~
If the use of printmat
is preferable (e.g., because it is more flexible) you can work around by using evalc
and strrep
. The trick here is to replace the spaces with other symbols (e.g. question marks) in the call to printmat
, store the output in a string via evalc
, and then use strrep
to replace the question marks by spaces. As a nice byproduct, you get the table as a string...
a = [ 11 22 33; 22 33 44];
x = evalc('printmat(matA, '''' , ''a b c'' , ''Title?One Title?Two Title?Three'')');
s = strrep(x, '?', ' ')
This results in
s =
Title One Title Two Title Three
a 11.00000 22.00000 33.00000
b 22.00000 33.00000 44.00000
However, the combination of printmat and evalc causes a lot of apostrophes...
Well, the documentation of printmat
tells you that
PRINTMAT(A,NAME,RLAB,CLAB) prints the matrix A with the row labels RLAB and column labels CLAB. NAME is a string used to name the
matrix. RLAB and CLAB are string variables that contain the row
and column labels delimited by spaces.
So spaces in the title are not natively supported.
As a workaround, you can use another separator that "looks like a space", for example, the unit separator:
printmat (
matA, '', 'one two', ...
['Title' char(31) 'One Title' char(31) 'Two Title' char(31) 'Three']);
output:
Test =
Title One Title Two Title Three
one 11.00000 22.00000 33.00000
two 22.00000 33.00000 44.00000
But as you see, this gets awkward real fast. It will also probably not look right when printed to file or some other output than the Matlab command window (terminal, for instance). You'll have to experiment a bit.
Personally I would just write my own, more general pretty-printer using cell
s and sprintf
with specific field-widths in the format string, as suggested by H.Muster (+1).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With