I agree with Matt - I bet there are faster ways to run your loop, and we can probably help out if you can describe what the loop is meant to do...
Nevertheless one way to keep your current code structure but speed it up a bit would be to pre-compute a buffer of randi integers between 0 and 2, rather than calling randi multiple times in the loop like this:
A=8;
B=12;
C=10;
bufferSz = 5000;
randBuffer = randi([0 2], bufferSz, B);
randUpTo = 1;
RandomMatriceB = zeros(A,B,C);
for ii=1:C;
for x=1:2:A-1;
[vals RandomMatriceA(x,:,ii)]=sort(rand(1,B),2);
done=false;
while ~done,
if randUpTo>bufferSz
randBuffer = randi([0 2], bufferSz, B);
randUpTo = 1;
end
NewRowRandomMatriceB = randBuffer(randUpTo,:);
randUpTo = randUpTo + 1;
done=sum(NewRowRandomMatriceB)<12;
end
RandomMatriceB(x,:,ii)=NewRowRandomMatriceB;
...
end
for h=2:2:A;
doneA=false;
while ~doneA,
[vals RandomMatriceA(h,:,ii)]=sort(rand(1,B),2);
doneB=false;
while ~doneB,
if randUpTo>bufferSz
randBuffer = randi([0 2], bufferSz, B);
randUpTo = 1;
end
NewRowRandomMatriceB = randBuffer(randUpTo,:);
randUpTo = randUpTo + 1;
doneB= sum(NewRowRandomMatriceB)<12;
end
RandomMatriceB(h,:,ii)=NewRowRandomMatriceB;
...
end
...
If you know the absolute maximum number of randi() integers you'll need, you won't even need the "check" that I put in that makes sure you don't try to access integers beyond the buffer size.
Did this speed things up for you Febri?
Oh, and do you initialize RandomMatriceB to a particular size? It doesn't look so..., so I bet that you'll get even more speedup by putting this line at the start of your code:
RandomMatriceB = zeros(A,B,C);
In fact, now that I look at your code a bit more, I think this would be the main issue.
Best Answer