Improving my code - I'm trying to generate a checkerboard of size (222,786); length of each size 20. My code did work but I feel the logic can be improved. Kindly help.

1 次查看(过去 30 天)
% Channel number 90 to 875
chan = 1:1:786;
no_of_chan=length(chan);
% ffid 77 to 298
ffid = 1:1:222;
no_of_ffid=length(ffid);
% Pre-declaring 'checker' - it is two dimensional
checker=zeros(no_of_ffid,no_of_chan);
% Parameter to switch between positive and negative trains within if
% statement
anomaly=-1;
% 1 cell = 100 metres
dimension=20;
% train is the size of one edge of one checker
train=ones(1,dimension);
for i=1:ceil((no_of_chan/dimension) - 1 )
if anomaly==1
train = [train ones(1,dimension)];
anomaly=-1;
else
train = [train -1*ones(1,dimension)];
anomaly=1;
end
end
for i=1:no_of_ffid
if anomaly==1
checker(i,:)=train(1:no_of_chan);
if rem(i,dimension)==0
anomaly=-1;
end
else
checker(i,:)=-1*train(1:no_of_chan);
if rem(i,dimension)==0
anomaly=1;
end
end
end
imshow(checker);

采纳的回答

John D'Errico
John D'Errico 2018-2-18
编辑:John D'Errico 2018-2-18
Shiver. Yes, it can be improved. :) Honestly, what you have done is highly convoluted. That is not bad for someone learning to program. But you are thinking in terms of loops. You are growing arrays dynamically. There are branches and tests in your code when none need exist.
You want to create an array, of size 222x786. Alternating black and white squares, of size 20? The white squares will be 1, the black squares filled with -1?
rdim = 222;
cdim = 786;
squaresize = 20;
[rind,cind] = ndgrid(0:rdim-1,0:cdim-1);
rind = floor(rind/squaresize);
cind = floor(cind/squaresize);
checker = 1 - 2*mod(rind + cind,2);
You want to start thinking in terms of arrays, and what you can do with them, how to work with them.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Image Processing and Computer Vision 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by