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?

27 views (last 30 days)
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

Accepted Answer

James Tursa
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

More Answers (2)

David Hill
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
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

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!