Once more... Avoid global variable!
Mostrar comentarios más antiguos
Hello together,
I'm writing many function which i often use during a matlab session. To make them a little more compfortalbe to use i'd like to use a data structure in some way, where i can store some preference data. The preference data is for example some input arguments the functions have in common. But because the values of these input arguments change from time to time, so i can not set it as default values in the function.
Global variables look perfect for this task, but i've read a lot of comments that global variables are bad and i'd rather avoid using them. But what other ways are there, to store my preference data and use it in different functions.
thank you for your help.
Rafael
1 comentario
Jan
el 29 de Nov. de 2017
This is a good question, +1. You state "Global variables look perfect for this task". The magic core in this formulation is "look": In fact, globals look like they solve the problems and they really do so - but in a long term view they will cause even more troubles, which can grow to a such severe level, that the code cannot be debugged or maintained anymore.
Respuesta aceptada
Más respuestas (3)
Image Analyst
el 29 de Nov. de 2017
0 votos
Jos (10584)
el 29 de Nov. de 2017
Take a look at the setappdata and getappdata. You can use the root handle to store variables.
setappdata(0,'MyVar',1:10)
per isakson
el 29 de Nov. de 2017
Editada: per isakson
el 29 de Nov. de 2017
preference.Viscosity = 1;
preference.Volume = 1;
preference.Pie = 3.141592653589793;
preference.Description = 'test';
params = examplefun( preference, 'Viscosity',2, 'Volume',3 );
and inspect params
>> params
params =
Viscosity: 2
Volume: 3
Pie: 3.1416
Description: 'test'
where
function ip = examplefun( nv, varargin )
ip = parse_pv_pairs( nv, varargin );
end
In examplefun you refer to the input arguments as ip.Viscosity, ip.Volume, ip.Pie and ip.Description.
This example doesn't fully meet your requirements, since the structure, preference, must contain all fields.
This solution may be developed further. Download CATSTRUCT, by Jos (10584) and run this modified example
preference.Viscosity = 1;
preference.Pie = 3.141592653589793;
params = examplefun( preference, 'Viscosity',2 );
and inspect params carefully
params =
Description: 'Default values'
Pie: 3.1416
Viscosity: 2
Volume: 12
>>
where
function ip = examplefun( nv, varargin )
warning('off','catstruct:DuplicatesFound')
default.Viscosity = 11;
default.Volume = 12;
default.Pie = 3.141592653589793;
default.Description = 'Default values';
nv = catstruct( default, nv );
ip = parse_pv_pairs( nv, varargin );
end
Both these FEX-contributions are good.
1 comentario
Rafael Kübler
el 29 de Nov. de 2017
Categorías
Más información sobre Scope Variables and Generate Names en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!