Write a function called \"multiply\" that takes in a number and produces an arra
ID: 3629492 • Letter: W
Question
Write a function called "multiply" that takes in a number and producesan array that represents the multiplication table for that number. A
multiplication table is a NxN array where the first row and column of the
array are the numbers from 0 to N inclusive. The rest of the table is
comprised of the products between that row number and that column number.For example, if the number is 4, the multiplication table would look like
this:
[0 1, 2, 3, 4
1, 1, 2, 3, 4
2,2,4, 6, 8
3, 3, 6, 9, 12
4, 4, 8, 12, 16]
Explanation / Answer
The function is as follows:
function multiply( n )
% multiply.m -- produces an
% n x n multiplication table on input n
A = zeros(n+1,n+1); % initialize the array A
for i = 0:n
for j = 0:n
% note: we index A by i+1 and j+1
% because we cannot have zero indices
if i == 0
% make the first row be the numbers 0 to n
A(i+1,j+1) = j;
elseif j == 0
% make the first column be the numbers 0 to n
A(i+1,j+1) = i;
else
% make the other entries be i*j
A(i+1,j+1) = i*j;
end
end
end
% print the multiplication table
disp(A);
end
Sample run 1:
>> multiply(3)
0 1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
Sample run 2:
>> multiply(4)
0 1 2 3 4
1 1 2 3 4
2 2 4 6 8
3 3 6 9 12
4 4 8 12 16
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.