# How to create Matrix [1 2 3 4; 2 4 6 8; 3 6 9 12; 4 8 12 16] without using loops or any functions using loops?

7 views (last 30 days)
Milosz Sobczyk on 2 Mar 2022
Commented: Davide Masiello on 10 Mar 2022
Hi, I'm trying to generate matrix
A = [1 2 3 4; 2 4 6 8; 3 6 9 12; 4 8 12 16]
without using any loops, but I have trouble finding solution

James Tursa on 9 Mar 2022
Edited: James Tursa on 9 Mar 2022
n = 4; % whatever
result = (1:n) .* (1:n)' % use implicit expansion row .* column
result = 4×4
1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16

David Hill on 2 Mar 2022
A = [1 2 3 4; 2 4 6 8; 3 6 9 12; 4 8 12 16];%what is wrong with this
You could also do something like:
n=4;
A=[1:n;2:2:2*n;3:3:3*n;4:4:4*n];
Milosz Sobczyk on 2 Mar 2022
Nothing is wrong. It was just an example I've written so I can expand a solution to NxN matrix. Thanks for help

Davide Masiello on 2 Mar 2022
Edited: Davide Masiello on 2 Mar 2022
To make it more general
n = 4;
a = 1:n;
A = repmat(1:n,n,1).*a';
For instance, if n = 6 this will generate
A =
1 2 3 4 5 6
2 4 6 8 10 12
3 6 9 12 15 18
4 8 12 16 20 24
5 10 15 20 25 30
6 12 18 24 30 36
not sure if repmat uses loops though, it probably does.
Davide Masiello on 10 Mar 2022
That's great, thanks!

R2021b

### Community Treasure Hunt

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

Start Hunting!