display matrix with text
8 views (last 30 days)
Show older comments
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 '
0 Comments
Answers (1)
Aditya
on 23 Jan 2025
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!
0 Comments
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!