laureapresa
laureapresa

Reputation: 179

Create a matrix with A(i, j) = i*j

I was practicing a Cody Problem:

At one time or another, we all had to memorize boring times tables. 5 times 5 is 25. 5 times 6 is 30. 12 times 12 is way more than you think.

With MATLAB, times tables should be easy! Write a function that outputs times tables up to the size requested.

I solved it with the code below.

function m = timestables(n)
for i =1:n
    for j = 1:n
        m(i,j) = i*j;
    end
end
end

Could I write it without for cycles and improve my score?

It may look stupid, but it is also useful for my work.

Upvotes: 2

Views: 1392

Answers (3)

Robert Seifert
Robert Seifert

Reputation: 25232

With ndgrid it's an easy task.

[x,y] = ndgrid(1:n)
m = x.*y

Alternatively use bsxfun, probably fastest solution, as bsxfun is always the fastest ;):

m = bsxfun(@times,1:n,(1:n).')

Upvotes: 5

LowPolyCorgi
LowPolyCorgi

Reputation: 5188

The simpler the better ; multiply the vectors:

m = (1:n)'*(1:n);

Best,

Upvotes: 5

Wouter Kuijsters
Wouter Kuijsters

Reputation: 840

if it is a minimum-length answer you're after, you might want to consider:

m = [1:n]'*[1:n];

But I suspect the bsxfun and ndgrid solutions thewaywewalk proposed are more efficient in terms of computation time.

Upvotes: 5

Related Questions