Filter löschen
Filter löschen

Add Headers to Matrix

2 Ansichten (letzte 30 Tage)
Bailey Smith
Bailey Smith am 5 Jun. 2018
Bearbeitet: Stephen23 am 6 Jun. 2018

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!

Akzeptierte Antwort

KSSV
KSSV am 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)

Weitere Antworten (1)

Stephen23
Stephen23 am 6 Jun. 2018
Bearbeitet: Stephen23 am 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:

Kategorien

Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by