display matrix with text

조회 수: 6 (최근 30일)
Anton Lipendin
Anton Lipendin 2018년 12월 13일
답변: Aditya 2025년 1월 23일
Hi,
I would like to display matrices in a command window as following:
A = [2 4;3 5];
B = [8 7;9 0];
C = A + B;
%part of code with solution to my question, which will result in displaying (in command window):
2 4 8 7 10 11
+ =
3 5 9 0 12 5
So notation feels very natural, like we would write it down on paper. Im curious to know if there is any possible solution without stringifying it to different lines like this?
'2 4 8 7 10 11'
' + = '
'3 5 9 0 12 5 '

답변 (1개)

Aditya
Aditya 2025년 1월 23일
Hi Anton,
To display matrices in the command window in a way that resembles how you might write them on paper, you can use MATLAB's 'fprintf' function to format the output. Here's a solution that aligns the matrices and the operation symbols (+ and =) as you described:
% Define matrices A and B
A = [2 4; 3 5];
B = [8 7; 9 0];
C = A + B;
% Call the function to display the matrices
display_matrices(A, B, C);
% Define a function to display the matrices
function display_matrices(A, B, C)
% Get the number of rows
[rows, ~] = size(A);
% Print each row of matrices A, B, and C
for i = 1:rows
fprintf('%d %d %d %d %d %d\n', A(i,1), A(i,2), B(i,1), B(i,2), C(i,1), C(i,2));
% Print the operation symbols after the first row
if i == 1
fprintf(' + = \n');
end
end
end
You can include an if-else condition within that function to modify it to show the matrix operation for different arithmetic operators as well.
I hope this helps!

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by