simple matrix

조회 수: 11 (최근 30일)
Austin
Austin 2011년 4월 20일
how can i write the code that makes a 10X10 matrix that looks like this
00000000000
00000000001
00000000011
00000000111
00000001111
00000011111
00000111111
00001111111
00011111111
00111111111
01111111111

답변 (3개)

Oleg Komarov
Oleg Komarov 2011년 4월 20일
fliplr(tril(ones(10),-1))
or
rot90(tril(ones(10),-1))
EDIT#2 (per Matt's suggestion)
Timings of:
a) fliplr
b) rot90
c) bsxfun
function M = fliptril(N,n)
% Obligatory timings....
times = zeros(N,3);
for ii = 1:N
tic
a = fliplr(tril(true(n),-1));
times(ii,1) = toc;
tic
b = rot90(tril(true(n),-1));
times(ii,2) = toc;
tic
c = bsxfun(@lt,(n:-1:1).',1:n);
times(ii,3) = toc;
end
m = mean(times(2:end,:));
M = m/min(m);
Timings N = 10,000, n = 100 (fliplr is faster):
>> M = fliptril(10000,100)
M =
1.0000 1.3644 2.2590
Timings N = 1,000, n = 500 (bsxfun is faster):
>> M = fliptril(1000,500)
M =
1.2637 1.7527 1.0000
  댓글 수: 7
Oleg Komarov
Oleg Komarov 2011년 4월 21일
WinVista 32, r2010b.
On http://www.mathworks.com/products/matlab/whatsnew.html r2009b bsxfun supports multithreading
Walter Roberson
Walter Roberson 2011년 4월 21일
I thought that perhaps calculating dt=1:n first and using flipud(dt(:)) and dt as the bsxfun arguments might speed things up, but on my tests they slow things down.
In 2008b, I find that the bsxfun approach is the slowest, and that the ratio gets worse as n increases.
Ah, correction: calculating dt and using flipud(dt(:)) is a bit faster than the original method once n passes about 2000. And by 4000, the bsxfun() methods are faster than rot90, with the ratio getting worse for rot90 as n increases.
Here are the ratios for n = 50000 (last column is with calculating 1:n and flipud() it)
1 1.74457576765052 1.1147589050359 1.11381126664567
Here are the ratios for n = 1000
1 1.27935606060606 1.82795055821372 1.83313397129187
thus rot90 is efficient for smaller n and bsxfun is not, but for larger n, rot90 and bsxfun have pretty much swapped efficiency ratios.

댓글을 달려면 로그인하십시오.


Walter Roberson
Walter Roberson 2011년 4월 20일
Look Ma, no rotate!
bsxfun(@lt,(10:-1:1).',1:10)

Jan
Jan 2011년 4월 26일
For larger matrices BUFFER is faster than FLIPLR(TRIL)) under Matlab 2009a:
n = 50;
data = ones(1, 2*n-1);
data(1:50) = 0;
M = buffer(data, n, n-1, 'nodelay');

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by