Effacer les filtres
Effacer les filtres

Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

How to make a matrix that descends with each row, but all columns are the same?

1 vue (au cours des 30 derniers jours)
Adam
Adam le 19 Jan 2016
Clôturé : MATLAB Answer Bot le 20 Août 2021
Hey, so I am trying to make a matrix that looks like this in general:
5 5 5 5 5
4 4 4 4 4
3 3 3 3 3
2 2 2 2 2
1 1 1 1 1
I vaguely remember from a class I took that I had to multiply a 1:5 matrix into a ones 5x5 matrix.. or something like that.
Could anyone help me figure out a way to get this type of matrix for any size? (for example, going from 255 down to 0 or something along those lines)
Thanks!
[Specifically, I need to make a matrix 500x500 that goes down from 255 to 0] So,
255 255 ... 255
254 254 ... 254
.
.
.
201 201 ... 201
etc.

Réponses (2)

the cyclist
the cyclist le 19 Jan 2016
Modifié(e) : the cyclist le 19 Jan 2016
One way:
N = 255;
M = 500;
vec = (N:-1:0)';
A = repmat(vec,1,M);

Stephen23
Stephen23 le 19 Jan 2016
Modifié(e) : Stephen23 le 19 Jan 2016
A simple matrix multiplication does the trick, no need for slow repmat:
>> (5:-1:1)' * ones(1,4)
ans =
5 5 5 5
4 4 4 4
3 3 3 3
2 2 2 2
1 1 1 1
This is a neat trick using indexing:
>> X = (5:-1:1)';
>> X(:,ones(1,4))
ans =
5 5 5 5
4 4 4 4
3 3 3 3
2 2 2 2
1 1 1 1
Both of these tend to be faster than repmat (100x100 matrix, 1000 iterations):
Elapsed time is 0.17901 seconds. % matrix multiply
Elapsed time is 0.157009 seconds. % indexing
Elapsed time is 1.37308 seconds. % repmat
  1 commentaire
the cyclist
the cyclist le 19 Jan 2016
Huh. I get very different relative timings:
N = 99;
M = 100;
vec = (N:-1:0)';
tic
for ii = 1:1000
A = vec*ones(1,M);
end
toc
tic
for ii = 1:1000
B = vec(:,ones(1,M));
end
toc
tic
for ii = 1:1000
C = repmat(vec,1,M);
end
toc
results in
Elapsed time is 0.014031 seconds.
Elapsed time is 0.007379 seconds.
Elapsed time is 0.004367 seconds.
and even more favorable results for repmat for larger arrays.

Cette question est clôturée.

Community Treasure Hunt

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

Start Hunting!

Translated by