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

采纳的回答

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 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by