5

Using Maps like in the example on MathWorks (see below) seem useful on first sight. But on second thought, they're a container structure, just as Matlab's struct variable types. I'm new to Maps and missing the advantage of when to use them as opposed to structs - to break the question down into some measurable parameters: In what some use-cases is using Maps vs structs faster and uses less lines of code?

from MathWorks docs, example:

months = {'Jan','Feb','Mar','Apr'};
rainfall = [327.2 368.2 197.6 178.4];
M = containers.Map(months,rainfall)

vs something similar with structs

months = {'Jan','Feb','Mar','Apr'};
rainfall = [327.2 368.2 197.6 178.4];
for ind=1:numel(months)
  s.(months{ind})=rainfall(ind);
end
user2305193
  • 2,079
  • 18
  • 39
  • 2
    This (interesting) question seems to be a duplicate of [this one](https://stackoverflow.com/q/34767016/2586922). Is it? – Luis Mendo Nov 26 '18 at 14:24
  • 1
    That second answer there has good info on differences. This Q asks for use cases where `Map` is better. I think the answer would be in any case where the difference with `struct` is relevant. – Cris Luengo Nov 26 '18 at 15:01
  • indeed absolute duplicate, I missed it, please close, thanks for being kind about this – user2305193 Nov 26 '18 at 15:23

1 Answers1

2

A container map is more or less an struct with a customized indexing. You can use them, when you prefer referring to an entry by a certain char for instance rather than an index. Let's say you want to recall the value of the rainfall for march.

%Declaration map, as you wrote

months = {'Jan','Feb','Mar','Apr'};
rainfall = [327.2 368.2 197.6 178.4];
M = containers.Map(months,rainfall);

M('Mar') % 197.6

As you see, you not just save a variable, but the reference (as a char, not in the typical way...) as well. For large amounts of data you shouldn'd use maps. Hence I'd recommend you to use maps when you specifically need char references and structs for the rest.

the map is (...) a dictionary, a mapping x --> y without any restrictions on x and y. A struct is a data structure, a way to save data in a logical way. - @hbaderts

Just to remind, if you can use a vector instead of a struct, definitely do so!

You will find other valuable informations about maps at this question.

Pablo Jeken Rico
  • 569
  • 5
  • 22
  • 3
    You can create a `stuct` that does exactly the same as the map in this answer. You'd index as `M.('Mar')`. A `struct` in MATLAB is also dictionary. The difference is that keys in a `struct` must be valid variable names, whereas keys in a `Map` can be anything, including numeric arrays. Other differences are less important, IMO. [This answer](https://stackoverflow.com/a/38933556/7328782) to the question you linked discusses the differences correctly. – Cris Luengo Nov 26 '18 at 17:18
  • I agree with Cris on this... thanks for the effort though – user2305193 Nov 26 '18 at 17:46