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

1 Ansicht (letzte 30 Tage)
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'
end
if i=2
run 'H2'
end
.
.
.
save(sprintf('Urbanv/Appu/AUG%d',i), 'GUD');
save(sprintf('Urbanv/Appu/AUI%d',i), 'I2');
end
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)
C=Hcombos(i2)
%for loop specific for H1
%Variable example: V1
end
end
And H2 will look like this
for i2=1:size(Hcombos, 1)
C=Hcombos(i2)
C2=Hcombos(i2,2)
%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
end
end

Akzeptierte Antwort

Rik
Rik am 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.
fh={@H1,@H2,@H3};
f=['Urbanv' filesep 'Appu'];
if ~exist(f,'dir'),mkdir(f);end
for n=1:numel(fh)
[GUD,I2]=fh{n}();
save(fullfile(f,sprintf('AUG%d',n)), var2str(GUD));
save(fullfile(f,sprintf('AUI%d',n)), var2str(I2));
end
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
varargout=cell(nargin,1);
for n=1:nargin
try varargout{n}=inputname(n);catch,varargout{n}='';end
if isempty(varargout{n}),err_flag=true;break,end
end
end
if err_flag
error('Invalid input and/or output.')
end
end

Weitere Antworten (0)

Produkte


Version

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by