performance - Best Practices with Initialization or Pre-allocation - MATLAB -
performance - Best Practices with Initialization or Pre-allocation - MATLAB -
my question doesn't depend expressly on 1 snippet of code, more conceptual.
unlike programming languages, matlab doesn't require variables initialized expressly before they're used. example, valid have halfway through script file define 'myvector':
myvector = vectora .* vectorb my question is: faster initialize variables (such 'myvector' above) 0 , assign values them, or maintain initializing things throughout program?
here's direct comparing of i'm talking about:
initializing throughout:
vara = 8; varb = 2; varc = vara - varb; vard = varc * varb; initializing @ start:
vara = 8; varb = 2; varc = 0; vard = 0; varc = vara - varb; vard = varc * varb; on 1 hand, seems bit of waste have these lines of code no reason. on other hand, though, makes little bit of sense faster allocate memory programme @ 1 time instead of spread out on runtime.
does have little insight?
copy , paste initializing @ start: code matlab editor window , warning looks -
and if go details, read -
explanation code not appear utilize assignment indicated variable. situation occurs when of next true: assignment overwrites value of variable before operation uses it. specified argument value contains typographical error, causing appear unused. code not utilize values returned function call... in our case, reason warning the code not utilize values. so, clarifies initialization/pre-allocation won't help case.
from experience, pre-allocation helps when need later on index part of it.
thus, if need index portion of varc store results, pre-allocation help. hence, create more sense -
varc = zeros(...) vard = zeros(...) varc(k,:) = vara - varb; vard(k,:) = varc * varb; again, while indexing if going beyond size of varc, matlab spend time trying allocate more memory space it, slow things bit. so, pre-allocate output variables maximum size think used storing results. but, if don't know size of results, in grab there , have append results output variable(s) , slow downwards things sure.
performance matlab
Comments
Post a Comment