How to display a string and matrix in MATLAB?

Hi all,
This question can look very basic to some experts of this forum, however the question bugs me as I am not an expert.
Say I initialize A= 3x3 unit matrix.
I want to display:
The result is: followed by matrix A.
I tried fprintf, but I guess it doesn't support matrix and I got errors.
disp() doesn't support displaying text+matrix.
Any idea how to do this?

1 Comment

A = eye(3); % Create a 3x3 identity matrix
fprintf('The result is:\n'); % Print a message before displaying the matrix
for i = 1:size(A,1) % Loop through each row of the matrix
fprintf('%.2f %.2f %.2f\n', A(i,:)); % Print each row with 2 decimal places
end

Sign in to comment.

 Accepted Answer

To display some text and a matrix, you can use two disp statements. This makes the code easy to understand and maintain.
For example, this code:
A = magic(3)
disp('The result is:')
disp(A)
Displays:
The result is:
8 1 6
3 5 7
4 9 2
If a one line solution is needed, you can use the num2str function to convert the matrix to a character array. This displays the contents of the array as a row vector though, changing the original shape of the matrix. To maintain the original shape of the matrix, use the first approach.
For example, this code:
A = magic(3)
disp(['The result is: [' num2str(A(:).') ']']) ;
Displays:
The result is: [8 3 4 1 5 9 6 7 2]

6 Comments

Well, to be fair,
result = A
might be easier/faster...
The OP wants to print the result and not store it in other variable ...
Sure!! Using two lines is certainly a way and thanks for it. However I am looking for something which can be done using single command in single line, as we can use fprintf to display many strings with many variables. Is any such way exists for matrices and strings?
It can be done even using fprintf but you need to know the matrix dimension and this approach is rather messy:
fprintf('The result is:\n%6.2f %6.2f %6.2f\n%6.2f %6.2f %6.2f\n%6.2f %6.2f %6.2f\n', A')
I really fail to see why it should be a single command …
A = magic(3)
% To put it on a single line (using a single command)
disp(['The result is: [' num2str(A(:).') ']']) ;
% and if you insist on using fprintf, try this:
fprintf('\nThe result is: [') ;
fprintf(' %d ', A) ;
fprintf(']\n') ;

Sign in to comment.

More Answers (3)

Same question, sometimes I wish to print sentence like 'The sum of matrix 1...n is N', which involves a matrix [1 .. n] and variable N, as well as strings. So how am I suppose to print this one out? Thank you!
A = eye(3); % Create a 3x3 identity matrix
fprintf('The result is:\n'); % Print a message before displaying the matrix
for i = 1:size(A,1) % Loop through each row of the matrix
fprintf('%.2f %.2f %.2f\n', A(i,:)); % Print each row with 2 decimal places
end

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!