MATLAB: fprintf/sprintf to print string + matrix

后端 未结 1 1542
慢半拍i
慢半拍i 2021-01-28 18:44

I wanted to know, if it\'s possible to print a string followed by a matrix, written in the classic form, for example:

                     5 5 9
>>your mat         


        
1条回答
  •  走了就别回头了
    2021-01-28 19:08

    If your matrix doesn't have to be on the same line as the text, you can do something as simple as replacing ; with \n in the output of mat2str:

    A=[1 2 3; 4 5 6; 7 8 9];
    intro_str = 'Your matrix is:\n';
    sprintf([intro_str strrep(mat2str(A),';','\n ')])
    

    Your matrix is:
    [1 2 3
     4 5 6
     7 8 9]
    

    If, however, you want to have them on the same line, the only way I see how this can be done is by computing the amount of tabs (\t) or spaces you need on every "non-intro" line, approximately like this:

    A=[1 2 3; 4 5 6; 7 8 9];
    
    intro_str = 'Your matrix is: ';
    
    %// ntabs = ceil(length(intro_str)/3);
    %// tab_blanks = cellstr(repmat('\t',size(A,2),ntabs));
    spaces = blanks(length(intro_str));
    space_blanks = repmat(spaces,size(A,2),1);
    
    mid_row = ceil(size(A,1)/2);
    
    %// tab_blanks(mid_row) = {intro_str};
    space_blanks(mid_row,:) = intro_str;
    
    final_str = [space_blanks repmat('%u\t',size(A,1),size(A,2)) repmat('\n',size(A,1),1)]';
    final_str = horzcat(final_str(:))';
    
    sprintf(final_str,A(:))
    

    ans =
    
                    1   4   7   
    Your matrix is: 2   5   8   
                    3   6   9
    

    0 讨论(0)
提交回复
热议问题