How to preallocate to decrease run time?
조회 수: 1 (최근 30일)
이전 댓글 표시
Re_1, Re_6, etc.. are have different dimensions i.e. Re_1 = 5000:20000, Re_6 = 200:10000, etc. I wrote this for loop to get the mean values at each value for Reynolds number. How can I preallocate this?
tot_Re = [Re_1 Re_6 Re_8 Re_9 Re_12 Re_13];
tot_Nu = [Nu_1 Nu_6 Nu_8 Nu_9 Nu_12 Nu_13];
Re_mean = 1:max(tot_Re);
for i = 1:max(tot_Re)
k = find(tot_Re == i);
Nu_mean(i) = mean(tot_Nu(k));
end
댓글 수: 0
채택된 답변
Greg
2018년 7월 19일
You can use unique to make your loop more robust. Then, logical indexing is much better than the find you've included. In fact, the find is completely unnecessary.
tot_Re = [Re_1 Re_6 Re_8 Re_9 Re_12 Re_13];
tot_Nu = [Nu_1 Nu_6 Nu_8 Nu_9 Nu_12 Nu_13];
Re_mean = 1:max(tot_Re); % You never use this...
[~,ind,~] = unique(tot_Re); % Using unique allows for gaps in values of tot_Re
Nu_mean = NaN(size(ind)); % Pre-allocate Nu_mean
for lp = 1:length(ind)
k = tot_Re == tot_Re(ind(lp)); % Leave indices as logicals
Nu_mean(lp) = mean(tot_Nu(k));
end
댓글 수: 0
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!