0

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 matrix is M = 1 4 2
                     2 1 3

using fprintf/sprintf.

0

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

Both the solution you proposed will be useful:thank you for the patience to answer me for the second time , @Dev-iL : )
@user5512412 - You're welcome. Also, please check this out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.