Info
This question is closed. Reopen it to edit or answer.
How to make a matrix that descends with each row, but all columns are the same?
1 view (last 30 days)
Show older comments
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.
0 Comments
Answers (2)
the cyclist
on 19 Jan 2016
Edited: the cyclist
on 19 Jan 2016
One way:
N = 255;
M = 500;
vec = (N:-1:0)';
A = repmat(vec,1,M);
0 Comments
Stephen23
on 19 Jan 2016
Edited: Stephen23
on 19 Jan 2016
>> (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 Comment
the cyclist
on 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.
This question is closed.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!