How to display a string and matrix in MATLAB?

조회 수: 2,013 (최근 30일)
Amit Kumar
Amit Kumar 2014년 2월 18일
답변: KAREN MEZA FLORES 2021년 10월 21일
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?

채택된 답변

Jos (10584)
Jos (10584) 2014년 2월 18일
편집: MathWorks Support Team 2018년 11월 27일
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
Jos (10584)
Jos (10584) 2014년 2월 18일
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') ;
Amit Kumar
Amit Kumar 2014년 2월 20일
Thanks!!

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

KAREN MEZA FLORES
KAREN MEZA FLORES 2021년 10월 21일
bro how do you even code - thanks

JIAN CUI
JIAN CUI 2016년 10월 26일
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!

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by