How to reduce execution time of for loops in MATLAB?
16 次查看(过去 30 天)
显示 更早的评论
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);
4 个评论
Stephen23
2018-1-9
"I initialized the variable before for loop"
MATLAB has no concept of initializing variables, as variables are all dynamically typed (and sized).
Did you preallocate the output array to its final size?
采纳的回答
Jan
2018-1-9
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.
3 个评论
Jan
2018-1-10
The please post the current version of the code. How could we suggest further changes otherwise?
更多回答(1 个)
Steven Lord
2018-1-9
If you profile your code, my guess is that the calls to convenc inside the nested loop take most of the time.
coded_data(k-(j*size(re_bin,1)/100),:)=convenc(re_bin(j*size(re_bin,1)/100,:),trellis);
Since the expression on the right side does not involve the inner loop variable k at all, don't recompute it every time. If you need to have that inner loop over k at all, compute that convenc result once and use that loop simply to assign the result you computed into a section of coded_data. You may need or want to use repmat to eliminate the loop entirely.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!