MATLAB: How to reduce execution time of for loops in MATLAB

for loop

I am new to Matlab. I am doing project in communication. While doing convolutional encoding with for loop it takes around 200 sec to execute. How to reduce the execution time?Do any of you guys know how to make the code run faster?
for i=1:size(re_bin,1)/100
coded_data1(i,:)=convenc(re_bin(i,:),trellis);
end
encodedData= coded_data1;
for j=1:100
for k=(j*size(re_bin,1)/100)+1: (j+1)*size(re_bin,1)/100
coded_data(k-(j*size(re_bin,1)/100),:)=convenc(re_bin(j*size(re_bin,1)/100,:),trellis);
end
encodedData1(:,:,j)= coded_data;
end
codedata=encodedData1;
finalCodeddata=cat(3,encodedData,codedata);

Best Answer

s100 = size(re_bin,1) / 100;
% Pre-allocate:
encodedData = zeros(s100, 0); % Better define 2nd dimension correctly
for i = 1:s100
encodedData(i, :) = convenc(re_bin(i,:), trellis);
end
encodedData1 = zeros(100, ???, 100); % Sorry, no idea what to insert for ???
for j = 1:100
tmp = convenc(re_bin(j * s100, :), trellis);
for k = (j*s100)+1:(j+1)*s100
encodedData1(k - j * s100, :, j) = tmp;
end
end
finalCodeddata = cat(3,encodedData, encodedData1);
The pre-allocation is essential for speed. It looks like "encodedData1" is very redundant. You should replace the loop over k by a repmat command:
for j = 1:100
tmp = convenc(re_bin(j * s100, :), trellis);
encodedData1(:, :, j) = repmat(tmp, 100, 1);
end
Do I see correctly, that the indices in "encodedData1(k - j * s100, :, j)" are 1:100 in each iteration? Sorry, I cannot test this by running your code, because I do not have the required toolbox.
Related Question