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?
28 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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
0 Comments
More Answers (2)
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];
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.
5 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!