How to preallocate to decrease run time?

조회 수: 1 (최근 30일)
Bixius
Bixius 2018년 7월 18일
답변: Greg 2018년 7월 19일
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

채택된 답변

Greg
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개)

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by