MATLAB: What is another logic that has execution time faster than randi

speed

here,part of my following code.
clc
clear all
A=8;
B=12;
C=10;
for ii=1:C;
for x=1:2:A-1;
%make first random matrice
[vals RandomMatriceA(x,:,ii)]=sort(rand(1,B),2);
done=false;
while ~done,
%make row of second random matrice
NewRowRandomMatriceB=randi([0 2],1,B);
%Make sure sum all element per row in RandomMatriceB <=11
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,
NewRowRandomMatriceB=randi([0 2],1,B);
doneB= sum(NewRowRandomMatriceB)<12;
end
RandomMatriceB(h,:,ii)=NewRowRandomMatriceB;
...
end
...
when I tried to use profile viewer to check my code. above part that makes my code took longer time. so, I want suggestion to speed my above code, specially in "randi"

Best Answer

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;
%make first random matrice
[vals RandomMatriceA(x,:,ii)]=sort(rand(1,B),2);
done=false;
while ~done,
%make row of second random matrice
if randUpTo>bufferSz
randBuffer = randi([0 2], bufferSz, B);
randUpTo = 1;
end
NewRowRandomMatriceB = randBuffer(randUpTo,:);
randUpTo = randUpTo + 1;
%Make sure sum all element per row in RandomMatriceB <=11
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.
Related Question