Can you have a function for multiple scripts that are growing in size?

1 view (last 30 days)
Joel Schelander
Joel Schelander on 12 Apr 2021
Answered: Rik on 14 Apr 2021
I have 36 scrpits that I run from a major script. My goal is to increase the performance as much as possible, since it now is really slow. Every script has the output GUD and I2 that I save as AUG1, AUG2... and AUI1, AUI2...
for i=1:36
if i=1
run 'H1'
if i=2
run 'H2'
save(sprintf('Urbanv/Appu/AUG%d',i), 'GUD');
save(sprintf('Urbanv/Appu/AUI%d',i), 'I2');
My problem is that the scripts are growing in size, so I do not know how to make a function that can replace the for loop above
For example, H1 now looks like this:
for i2=1:size(Hcombos, 1)
%for loop specific for H1
%Variable example: V1
And H2 will look like this
for i2=1:size(Hcombos, 1)
%for loop specific for H1
%Variable example: V1
%for loop specific for H2
%Variable example: V2
%for loop that ensures that V1 and V2 are not the same

Accepted Answer

Rik on 14 Apr 2021
Scripts are not for real work, use functions instead. Functions allow you to write code that solves a specific problem. You can document the uses and test it. As long as you don't do a Bad Thing by using evalin(__,'caller'), the function doesn't depend on the calling environment. There is a reason almost all code provided by Mathworks is in a function (most if not all exceptions are examples).
If you create a list of function handles, you can even make that loop more compact (and you should really consider renaming these scripts so their purpose is clear).
Using var2str allows you to use the tools that Matlab provides for detecting the use of variables and will allow you to rename them easily.
f=['Urbanv' filesep 'Appu'];
if ~exist(f,'dir'),mkdir(f);end
for n=1:numel(fh)
save(fullfile(f,sprintf('AUG%d',n)), var2str(GUD));
save(fullfile(f,sprintf('AUI%d',n)), var2str(I2));
H1 ran H2 ran H3 ran
%make sure the function signatures exist and work
function [a,b]=H1,a=rand;b=rand;disp('H1 ran'),end
function [a,b]=H2,a=rand;b=rand;disp('H2 ran'),end
function [a,b]=H3,a=rand;b=rand;disp('H3 ran'),end
function varargout=var2str(varargin)
%Analogous to func2str, return the variable names as char arrays, as detected by inputname.
%This returns an error for invalid inputs and if nargin~=max(1,nargout).
%You can use comma separated lists to create a cell array:
% out=cell(1,2);
% foo=1;bar=2;
% [out{:}]=var2str(foo,bar);
err_flag= nargin~=max(1,nargout) ;
if ~err_flag
for n=1:nargin
try varargout{n}=inputname(n);catch,varargout{n}='';end
if isempty(varargout{n}),err_flag=true;break,end
if err_flag
error('Invalid input and/or output.')

More Answers (0)

Community Treasure Hunt

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

Start Hunting!