Add Headers to Matrix
2 views (last 30 days)
Show older comments
I made a multiplication table and want to add headers to it. This is my code:
clear; clc; n = input('Select a value for n: '); m = zeros(n); for column = 1:1:n for row = 1:1:n num = row*column; m(column,row) = num; end end disp(m)
I would like it to have a header over the top and down the left side like a real multiplication chart. How would I go about doing this? For example, say the user enters 3. I want it to look like:
1 2 3 1 1 2 3 2 2 4 6 3 3 6 9
Thank you so much in advance!
0 Comments
Accepted Answer
KSSV
on 6 Jun 2018
n = input('Select a value for n: ');
m = zeros(n);
for column = 1:1:n
for row = 1:1:n
num = row*column;
m(column,row) = num;
end
end
iwant = zeros(n+1,n+1) ;
iwant(2:end,1) = 1:n ;
iwant(1,2:end) = 1:n ;
iwant(2:end,2:end) = m ;
iwant = num2str(iwant) ;
iwant(1,1) = 'X' ;
disp(iwant)
0 Comments
More Answers (1)
Stephen23
on 6 Jun 2018
Edited: Stephen23
on 6 Jun 2018
No loops are required, just use MATLAB's ability to work with complete matrices:
n = str2double(input('Select a value for n: ','s')); % safer to use 's' option.
v = 1:n;
m = [v;v(:)*v];
f = repmat('%5d',1,n);
fprintf(['x |',f,'\n'],v)
fprintf('--|%s\n',repmat('-',1,n*5))
fprintf(['%-2d|',f,'\n'],m)
Which displays this in the command window:
Select a value for n: 6
x | 1 2 3 4 5 6
--|------------------------------
1 | 1 2 3 4 5 6
2 | 2 4 6 8 10 12
3 | 3 6 9 12 15 18
4 | 4 8 12 16 20 24
5 | 5 10 15 20 25 30
6 | 6 12 18 24 30 36
If you want to put headers in a variable stored in MATLAB memory, then I highly recommend using tables:
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!