BMG
BMG

Reputation: 87

Triangular Multiplication Table

I'm working on a program that's supposed to write out the multiplication table as shown in the picture.

Desired output

This is what I've done

A = (1:10)'*(1:10);
tril (A)

And this is my output. Is there a way I can do this without the zeros? Or should I go with a different approach? Any help is greatly appreciated.

     1     0     0     0     0     0     0     0     0     0
     2     4     0     0     0     0     0     0     0     0
     3     6     9     0     0     0     0     0     0     0
     4     8    12    16     0     0     0     0     0     0
     5    10    15    20    25     0     0     0     0     0
     6    12    18    24    30    36     0     0     0     0
     7    14    21    28    35    42    49     0     0     0
     8    16    24    32    40    48    56    64     0     0
     9    18    27    36    45    54    63    72    81     0
    10    20    30    40    50    60    70    80    90   100

Upvotes: 1

Views: 880

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112679

Your approach is good, but if you want to avoid the zeros you want strings, not numbers. For example,

>> n = 10;
>> char(arrayfun(@(k) {sprintf('%i ', k:k:k^2)}, 1:n).')
ans =
1                              
2 4                            
3 6 9                          
4 8 12 16                      
5 10 15 20 25                  
6 12 18 24 30 36               
7 14 21 28 35 42 49            
8 16 24 32 40 48 56 64         
9 18 27 36 45 54 63 72 81      
10 20 30 40 50 60 70 80 90 100 

How it works

sprintf('%i ', k:k:k^2) generates each row of the table as a string. cellfun is used to iterate over all rows. The rows are packed into a cell array of strings, and that cell array is converted to a char matrix, which automatically pads with spaces.

Upvotes: 1

Geoff
Geoff

Reputation: 1212

Here's one way:

A=tril((1:10)'*(1:10))
A(A==0)=NaN;              
S=num2str(A);
S(S==78|S==97)=' '

The second line distinguishes plain old '0' from a pesky '0' in, say, '20'.

The third line converts the array to a string.

The last line replaces capital 'N' (character 78) and lowercase 'a' (character 97) with blank space.

Upvotes: 3

Related Questions