performance - Code organization Matlab -
this question has answer here:
i write program @ matlab. in .m file. , it's 300+ strings of code now, became not comfortable reading. idea use in c++: want create local functions @ end of file , put pieces of code them. easy read , consist of logical parts.
but faced fact local functions can created in body of other function! can't create this:
x = 1; y = 2; z = mylocalfnc(x,y); function res = mylocalfnc (a,b) res = a.*b; end
this generate error:
function definitions not permitted in context.
i can including whole code 1 function:
function mybigfcn x = 1; y = 2; z = mylocalfnc(x,y); end function res = mylocalfnc (a,b) res = a.*b; end
but variables became local , return workspace nothing. modify input/output function time create variable - don't think walk right way... here described advantages , disadvantages of method.
i know can create function in additional .m file, save , use in script - ok, lot of them single-operation, don't want create new files.
my question other methods of code organizing?
one option, if don't mind saving file locally, restructure code multiple functions (all in same file) , pass necessary variables output. have short script calls function , creates necessary variables.
for example, script looks this
numpoints = 5; = randn(numpoints); b = sin(a); c = + b;
you restructure like
function data = main() data.numpoints = 5; data.a = geta(data.numpoints); data.b = getb(data.a); data.c = getc(data.a, data.b); function = geta(numpoints) = randn(numpoints); function b = getb(a) b = sin(a); function c = getc(a, b) c = + b;
and create script file looks like
data = main();
you have struct called data
contains of variables. if want them contained in separate variables (i.e. not in struct) there couple of ways it. 1 unpack them manually,
a = data.a; b = data.b; c = data.c; clear data;
another save struct, , reload (this has advantage of keeping copy of workspace used fun of function, later analysis).
save('workspace.mat', '-struct', 'data'); load('workspace.mat');
Comments
Post a Comment