필터 지우기
필터 지우기

Add Headers to Matrix

조회 수: 2 (최근 30일)
Bailey Smith
Bailey Smith 2018년 6월 5일
편집: Stephen23 2018년 6월 6일

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!

채택된 답변

KSSV
KSSV 2018년 6월 6일
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)

추가 답변 (1개)

Stephen23
Stephen23 2018년 6월 6일
편집: Stephen23 2018년 6월 6일
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:

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by