Search code examples
matlabdictionarycontainers

Matlab Container.Map behavior vs Dictionary


I had to remove in my existing script, all dictionary structures to container.Map because I must run my app on old matlab version (<=R2012b)

I have a call member on an instance like this :

% Declaration of container map
app.MC = containers.Map('KeyType', 'double', 'ValueType', 'any');

% Create first instance of Monte Carlo object with the key -15. 
% Monte_Carlo is a class herited from Handle
app.MC(-15) = Monte_Carlo(Nb_Iterations_par_depointage, consigne_depointage_y);

% Call member on Monte_Carlo instance
app.MC(-15).Enregistre_Reference_Dephasage_Secteur(a, b);

When I execute this, I get the following error on the last line

Too many output arguments.

But if I replace the declaration by

% Declaration of container map
app.MC = dictionary;

All works fine.

I checked the types, and in both cases class(app.MC(-15)) returns 'Monte_Carlo'

If I proceed in 2 times with an intermediate variable which sotres the app.MC(-15) instance, it works :

% Declaration of container map
app.MC = containers.Map('KeyType', 'double', 'ValueType', 'any');
    
% Create first instance of Monte Carlo object with the key -15
app.MC(-15) = Monte_Carlo(Nb_Iterations_par_depointage, consigne_depointage_y);
    
% Intermediate variable in order to call member with container.Map
Z = app.MC(-15);

% Now I can do that, and it works 
Z.Enregistre_Reference_Dephasage_Secteur(a, b);

Do you know why I can access to the member of the object directly with dictionary, and I can't with container.Map ?


Solution

  • This is simply because of the way that containers.Map is implemented. It’s one of the many issues with it that prompted them to add dictionary. You’re not doing anything wrong.

    If

    Z.Enregistre_Reference_Dephasage_Secteur(a, b);
    

    modifies Z, then Z must be a handle object for this to work. If it’s not a handle object (the class is derived from handle) then you need to write the Z back into the container after modifying it, because you modified a copy:

    Z = app.MC(-15);
    Z = Z.make_a_change(a, b);
    app.MC(-15) = Z;
    

    (But do note that in your code, Z is either a handle object or it’s not modified, so that code is always correct.)