1. What about object oriented programming ?
One of the most significant upgrades of Matlab during the last few years was made with object-oriented programming. Indeed, Matlab changed its syntax dedicated to object-oriented programming and added concepts and rules that already exist in other object languages, like classes and references. A class-defining file is recognised thanks to the keyword classdef. A Matlab class describes properties, methods and events. It can be organised in a package to manage the name space and facilitate the syntax during their calls. References to objects are possible with the keyword handle and allow object handling without copying it. However, since the R2011a release, the class copyable brings a new behavior when copying a handle class.
In addition, to implement lookup tables, Matlab has created, since R2008b, a new kind of data: containers.Map. It is a good point for Python or Perl programmers who are familiar with these data types. From now on, it is possible to index a table with a “key”. A key can be a real number or a string instead of a positive integer, so it means more flexibility to access data. You can store all kind of data (matrix, structures, cells, strings, object and even other Maps). This type of data combines readability of structure and ‘container simplicity’ of cell arrays.
% Building % containers.Map
myKeys = {‘key1′,’key2′,’key3’};
myValues = {ones(3),‘stuff’,123};
myObject = containers.Map(myKeys, myValues);
% Or else
myObject2 = containers.Map({‘key1′,’key2′,’key3’},{ones(3),‘stuff’,123});
% Get and display elements in container
Key = keys(myObject)
Values= values(myObject)
Values1 = myObject(‘key1’)
Key =
‘key1’ ‘key2’ ‘key3’
Values =
[3×3 double] ‘stuff’ [123]
Values1 =
1 1 1
1 1 1
1 1 1
When programming, cleaning tasks (closing files, restoring the default path…) can be specified after running a function thanks to the object: onCleanup.
%% Exemple onCleanUp to ensure file closure in case of error
function strText = lireFichier(nomFichier)
% Open file while reading it
fid = fopen(nomFichier, ‘rt’);
if fid<0
error(‘lireFichier:ImpossibleOuvrirFichier’, …
‘Impossible d”ouvrir %s\n’, nomFichier);
end
% Add on CleanUp object to close file when returning function
objCleanup = onCleanup(@() fermeture(fid, nomFichier));
% Read file
strText = fread(fid, ‘*char’)’;
% Send error if the file is empty
if isempty(strText)
error(‘lireFichier:FichierVide’, ‘Le fichier est vide’);
end
%% Function that is run by objCleanUp when ending the function
function fermeture(fileID, fileName)
fclose(fileID);
fprintf(‘objCleanup : fermeture du fichier “%s”\n’, fileName);
end
end