Add Headers to Matrix
Afficher commentaires plus anciens
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!
Réponse acceptée
Plus de réponses (1)
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:
Catégories
En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!