Searching online, there are multiple discussions about good programming practices, e.g. Michael Robbins from MIT , Raviteja's MATLAB Answers Sept 2011 question , Brett Schoelson's Jan 2011 blogpost , Michael Robbins' MATLAB Newsgroup March 2000 discussion , and some things appear to be a matter of opinion, but I wanted to hear your thoughts about minimizing lines of code, something I didn't see discussed there. Does passing data to a user-defined function cost more speed than repeating built-in functions?
For example, consider the following function. At one point I change a string's value and then repeat the loop, i.e. copy-pasting code rather than creating another function within my script. Because the code is identical, should it go in its own function? That would require less lines of code, but it would require passing more data to another function, presumably creating a second copy of it, temporarily requiring more RAM. Am I correct in thinking it will execute faster if I repeat the code within this function rather than create a second function called within it?
Or, even if it would execute faster, is it still better practice to use a function because then the code only needs to be edited once rather than in multiple locations?
function youtput = ExtractDataFromCellArray(maxsize,newvoldata,Organ)% We must produce a table containing the dosed volumes and the dose
% intervals for each element in these vectors. This table should have
% variables Volumes, DistType, and DoseInterval.
youtput = table(zeros(maxsize,1),cell(maxsize,1),cell(maxsize,1),... 'VariableNames',{'Volumes' 'DistType' 'DoseInterval'}); index = 0; DistType = 'planned'; for loop = 1:numel(newvoldata) if ~isempty(newvoldata{loop}) matchingindices = strcmpi(newvoldata{loop}.DistributionType,DistType)... & strcmpi(newvoldata{loop}.Organ,Organ); SectionLength = length(find(matchingindices)); youtput(index+1:SectionLength+index,:) = table( ... newvoldata{loop}.Volume(matchingindices), ... newvoldata{loop}.DistributionType(matchingindices), ... newvoldata{loop}.DoseInterval(matchingindices)); index = index + SectionLength; end end DistType = 'blurred'; clear matchingindices % just to be safe
for loop = 1:numel(newvoldata) if ~isempty(newvoldata{loop}) matchingindices = strcmpi(newvoldata{loop}.DistributionType,DistType)... & strcmpi(newvoldata{loop}.Organ,Organ); SectionLength = length(find(matchingindices)); youtput(index+1:SectionLength+index,:) = table( ... newvoldata{loop}.Volume(matchingindices), ... newvoldata{loop}.DistributionType(matchingindices), ... newvoldata{loop}.DoseInterval(matchingindices)); index = index + SectionLength; end end youtput(youtput.Volumes==0,:)=[];end
Best Answer