simple matrix
14 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuestas (3)
Oleg Komarov
el 20 de Abr. de 2011
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 comentarios
Oleg Komarov
el 21 de Abr. de 2011
WinVista 32, r2010b.
On http://www.mathworks.com/products/matlab/whatsnew.html r2009b bsxfun supports multithreading
Walter Roberson
el 21 de Abr. de 2011
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.
Jan
el 26 de Abr. de 2011
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');
0 comentarios
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!