How do I get a specific number of successive ones in my binary matrix?

1 view (last 30 days)
I would like to create a binary 3D matrix (60x96x10), where there are 60*96 ones finally, and their position is randomized and unique. Everytime a 1 occurs, i would like 2 more ones to come after it, but my code is glitching and gives 4 or 5 ones everytime I run it. What is wrong with my code?
function cubefinal = sensingmatrix3d(time)
exposure=zeros(60,96,10);
if time==3
for j=1:size(exposure,1);
for jj=1:size(exposure,2);
randnum=randi([1 8]);
exposure(j,jj,randnum:randnum+2)=1;
end
end
end
end

Accepted Answer

the cyclist
the cyclist on 4 Aug 2015
I ran the following test code (which fills in 1's exactly as yours does). It displays a few lines at random, and also checks that the total number of 1's is the expected value.
exposure = zeros(60,96,10);
for j=1:size(exposure,1);
for jj=1:size(exposure,2);
randnum=randi([1 8]);
exposure(j,jj,randnum:randnum+2)=1;
% Randomly select some rows to spot-check
if rand < 0.003
checkRow = reshape(exposure(j,jj,:),[1 10])
end
end
end
% Confirm that there are the expected number of ones in the array
sum(exposure(:)) == 60*96*3
I'm not sure what you think is wrong, but the code does seem to do what you want it to.

More Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 4 Aug 2015
exposure=zeros(60,96,10);
[n,m,p]=size(exposure)
[xx,yy]=ndgrid(1:n,1:m);
randnum=cell2mat(arrayfun(@(x) x:x+2,randi([1 8],1,60*96),'un',0));
xx=repmat(xx(:)',3,1)
yy=repmat(yy(:)',3,1)
idx=sub2ind([n,m,p],xx(:),yy(:),randnum');
exposure(idx)=1

Tags

Community Treasure Hunt

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

Start Hunting!