Multiplication tables: Difference between revisions
Content deleted Content added
No edit summary |
→{{header|MATLAB}}: Optimized the solution code |
||
Line 906: | Line 906: | ||
=={{header|MATLAB}}== |
=={{header|MATLAB}}== |
||
timesTable.m: (creates Times Table of N degree) |
|||
⚫ | |||
function M=timestable(N) |
|||
A=zeros(N+1,N+1); |
|||
B=zeros(N+1,N+1); |
|||
C=zeros(N+1,N+1); |
|||
for i=1:N |
|||
A(i+1,1)=i; |
|||
for j=1:N |
|||
A(1,j+1)=j; |
|||
B(i+1,j+1)=i*j; |
|||
⚫ | |||
end |
|||
i=1; |
|||
for j=1:N |
|||
C(i,j)=1; |
|||
end |
|||
j=1; |
|||
for i=1:N+1 |
|||
C(i,j)=1; |
|||
end |
|||
for i=2:N+1 |
|||
for j=2:N+1 |
|||
if i<=j |
|||
C(i,j)=1; |
|||
⚫ | |||
⚫ | |||
end |
|||
M=A+(B.*C); |
|||
⚫ | |||
<lang MATLAB>function table = timesTable(N) |
|||
for N=12 |
|||
table = [(0:N); (1:N)' triu( kron((1:N),(1:N)') )]; |
|||
<lang> |
|||
⚫ | |||
>>timestable(12) |
|||
A minimally vectorized version of the above code: |
|||
<lang MATLAB>function table = timesTable(N) |
|||
%Generates a column vector with intigers from 1 to N |
|||
rowLabels = (1:N)'; |
|||
⚫ | |||
%Generate a row vector with integers from 0 to N |
|||
columnLabels = (0:N); |
|||
⚫ | |||
%Generate the multiplication table using the kronecker tensor product |
|||
%of two vectors one a column vector and the other a row vector |
|||
table = kron((1:N),(1:N)'); |
|||
%Make it upper triangular and concatenate the rowLabels and |
|||
%columnLabels to the table |
|||
table = [columnLabels; rowLabels triu(table)]; |
|||
⚫ | |||
⚫ | |||
For N=12 the output is: |
|||
<lang MATLAB>timesTable(12) |
|||
ans = |
ans = |