San*_*ong 1 matlab image-processing matrix diagonal
这是我想要的结果.位分辨率是256 x 256.
// assign default background to white.
img = ones(256, 256);
Run Code Online (Sandbox Code Playgroud)
结果示例:
0 1 1 1
0 0 1 1
0 0 0 1
0 0 0 0
Run Code Online (Sandbox Code Playgroud)

有没有办法可以在MATLAB中使用zeros()和ones()函数来实现这个结果?我该怎么做循环?
结果是eye()函数可以做的事情,但它只做一条对角线.我想要一条分开0和1的对角线.
如果您关心性能,可以尝试bsxfun基于方法 -
n = 256; %// resolution of img would be nxn
img = bsxfun(@le,[1:n]',0:n-1);
Run Code Online (Sandbox Code Playgroud)
num_runs = 50000; %// Number of iterations to run benchmarks
n = 256; %// nxn would be the resolution of image
%// Warm up tic/toc.
for k = 1:50000
tic(); elapsed = toc();
end
disp(['For n = ' num2str(n) ' :'])
disp('---------------------- With bsxfun')
tic
for iter = 1:num_runs
out1 = bsxfun(@le,[1:n]',0:n-1); %//'
end
time1 = toc;
disp(['Avg. elapsed time = ' num2str(time1/num_runs) ' sec(s)']),clear out1
disp('---------------------- With triu')
tic
for iter = 1:num_runs
out2 = triu( true( n ), 1 );
end
time2 = toc;
disp(['Avg. elapsed time = ' num2str(time2/num_runs) ' sec(s)']),clear out2
Run Code Online (Sandbox Code Playgroud)
结果
For n = 256 :
---------------------- With bsxfun
Avg. elapsed time = 0.0001506 sec(s)
---------------------- With triu
Avg. elapsed time = 4.3082e-05 sec(s)
For n = 512 :
---------------------- With bsxfun
Avg. elapsed time = 0.00035545 sec(s)
---------------------- With triu
Avg. elapsed time = 0.00015582 sec(s)
For n = 1000 :
---------------------- With bsxfun
Avg. elapsed time = 0.0015711 sec(s)
---------------------- With triu
Avg. elapsed time = 0.0019307 sec(s)
For n = 2000 :
---------------------- With bsxfun
Avg. elapsed time = 0.0058759 sec(s)
---------------------- With triu
Avg. elapsed time = 0.0083544 sec(s)
For n = 3000 :
---------------------- With bsxfun
Avg. elapsed time = 0.01321 sec(s)
---------------------- With triu
Avg. elapsed time = 0.018275 sec(s)
Run Code Online (Sandbox Code Playgroud)
对于您的256x256大小问题,triu可能是首选方法,但对于足够大的数据量,可以考虑bsxfun提高50%的性能.