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

6 vues (au cours des 30 derniers jours)
tash7827
tash7827 le 4 Août 2015
Commenté : tash7827 le 4 Août 2015
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

Réponse acceptée

the cyclist
the cyclist le 4 Août 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.

Plus de réponses (1)

Azzi Abdelmalek
Azzi Abdelmalek le 4 Août 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

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by