Reputation: 168
I am new in Matlab but I am trying. I have the following code:
for t = 1:size(data,2)
b = data(t)/avevalue;
if b >= 1
cat1 = [repmat((avevalue),floor(b),1)',mod(data(t),15)];
else
cat1 = data(t);
end
modified = [modified,cat1];
end
The answer for
data=[16 18 16 25 17 7 15];
avevalue=15;
is
15 1 15 3 15 1 15 10 15 2 7 15 0
But when my array is more than 10000 elements it working very, impossibly slow (for 100000 nearly 3 minutes, for example). How can I increase its speed?
Upvotes: 1
Views: 62
Reputation: 5822
There are two main reasons for the slowness:
you can improve runtime by trying the following approach:
%auxilliary array
divSumArray = ceil((data+1)/avevalue);
%defines output array
newArr = ones(1,sum(divSumArray))*avevalue;
%calculates modulo
moduloDataIndices = cumsum(divSumArray);
%assigning modulo in proper location
newArr(moduloDataIndices) = mod(data,avevalue);
the final result
15 1 15 3 15 1 15 10 15 2 7 15 0
Time measurement
I measured runtime for the following input:
n = 30000;
data = randi([0 99],n,1);
avevalue=15;
original algo:
Elapsed time is 11.783951 seconds.
optimized algo:
Elapsed time is 0.007728 seconds.
Upvotes: 2