필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

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

조회 수: 1 (최근 30일)
Adam
Adam 2016년 1월 19일
마감: MATLAB Answer Bot 2021년 8월 20일
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.

답변 (2개)

the cyclist
the cyclist 2016년 1월 19일
편집: the cyclist 2016년 1월 19일
One way:
N = 255;
M = 500;
vec = (N:-1:0)';
A = repmat(vec,1,M);

Stephen23
Stephen23 2016년 1월 19일
편집: Stephen23 2016년 1월 19일
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
the cyclist
the cyclist 2016년 1월 19일
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.

이 질문은 마감되었습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by