フィルターのクリア

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