Search code examples
arraysmatlabmatrixcenter

string - num2str auto width format in MATLAB


Sorry for my dumb question, i'm new on matlab. I have an matrix array like this

num = [
    4.2, 3, 5;
    3, 12.1, 3.4;
    2, 5.22, 4
]

I just want to display it using center align format, like the example below

enter image description here

but number in num array is dynamic, sometimes on each row contain up to 4 or more number like this

num = [
    4.2, 3, 5, 7.899;
    3, 12.1, 3.4, 89;
    2, 5.22, 4, 9.1
]

I was trying using num2str() function, but it doesn't fit on my case because my data is dynamic (sometimes it always have 2 or 3 more digit of decimal number) here is my code:

num2str('%10.1f \t %10.1f \t %10.1f \n', num);

Is there any other function beside using num2str(), because my array data is dynamic


Solution

  • You can centre a string with strjust. Here, I build the individual elements in a loop with sprintf and add a newline character:

    num = [
    4.2, 3, 5, 7.899;
    3, 12.1, 3.4, 89;
    2, 5.22, 4, 9.1
    ];
    
    % Loop over rows (ii) and columns (jj) of num
    output = '';
    for ii = 1:size(num,1)
      for jj = 1:size(num,2)
        output = [output, strjust(sprintf('%10.4g',num(ii,jj)),'center')];
      end % for jj
      output = [output, '\n'];
    end % for ii
    fprintf(output)
    

    Output:

       4.2        3         5       7.899   
        3        12.1      3.4        89    
        2        5.22       4        9.1    
    

    You can put this into e.g. an image by using a final call to sprintf:

    text(0.5, 0.5, sprintf(output))
    

    Note that this uses a non-fixed width font, so a long line might not look centre-justified. This can be seen by using

    num = [999, 999, 999, 999; 1, 1, 1, 1];
    

    MATLAB version R2014a.