matlaboperatorsdot-operator

What does the . operator do in matlab?


I came across some matlab code that did the following:

thing.x=linspace(...

I know that usually the . operator makes the next operation elementwise, but what does it do by itself? Is this just a sub-object operator, like in C++?


Solution

  • Yes its subobject.

    You can have things like Roger.lastname = "Poodle"; Roger.SSID = 111234997; Roger.children.boys = {"Jim", "John"}; Roger.children.girls = {"Lucy"};

    And the things to the right of the dots are called fields.

    You can also define classes in Matlab, instatiate objects of those classes, and then if thing was one of those objects, thing.x would be an instance variable in that object.

    The matlab documentation is excellent, look up "fields" and "classes" in it.

    There are other uses for ., M*N means multiploy two things, if M, N are both matrices, this implements the rules for matrix multiplication to get a new matrix as its result. But M.*N means, if M, N are same shape, multiply each element. And so no like that with more subtleties, but out of scope of what you asked here.

    As @marc points out, dot is also used to reference fields and subfields of something matlab calls a struct or structure. These are a lot like classes, subclasses and enums, seems to me. The idea is you can have a struct data say, and store all the info that goes with data like this:

    olddata = data; % we assume we have an old struct like the one we are creating, we keep a reference to it
    
    data.date_created=date();
    data.x_axis = [1 5 2 9];
    data.notes = "This is just a trivial example for stackoverflow.  I didn't check to see if it runs in matlab or not, my bad."
    data.versions.current = "this one";
    data.versions.previous = olddata;
    

    The point is ANY matlab object/datatype/whatever you want to call it, can be referenced by a field in the struct. The last entry shows that we can even reference another struct in the field of a struct. The implication of this last bit is we could look at the date of creation of the previous verions:

    data.versions.previous.date_created
    

    To me this looks just like objects in java EXCEPT I haven't put any methods in there. Matlab does support java objects which to me look a lot like these structs, except some of the fields can reference functions.