这是我想要的结果。
位分辨率为256 x 256
。
// assign default background to white.
img = ones(256, 256);
示例结果:
0 1 1 1
0 0 1 1
0 0 0 1
0 0 0 0
我有没有办法在MATLAB中使用zeros()
和ones()
函数来实现这个结果?我该怎么做循环?
结果是eye()
函数可以做的事情,但它只做一条对角线。我想要一条分开0和1的对角线。
答案 0 :(得分:11)
您正在寻找triu
功能
img = triu( ones( 256 ), 1 );
答案 1 :(得分:8)
如果您关心效果,可以尝试基于bsxfun
的方法 -
n = 256; %// resolution of img would be nxn
img = bsxfun(@le,[1:n]',0:n-1);
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
<强>结果
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)
对于256x256
大小的问题,triu
可能是首选方法,但对于足够大的数据量,人们可以查看bsxfun
,性能提升高达50%。