Search code examples
matlabcopy-on-writematlab-table

Exploit Matlab copy-on-write by ensuring function arguments are read-only?


Background

I'm planning to create a large number of Matlab table objects once, so that I can quickly refer to their contents repeatedly. My understanding is that each table variable/column is treated in copy-on-write manner. That is, if a table column is not modified by a function, then a new copy is not created.

From what I recall of C++ as of 1.5 decades ago, I could ensure that the code for a function does not modify its argument's data by using constant-correctness formalism.

The specific question

I am not using C++ in these days, but I would like to achieve a similar effect of ensuring that the code for my Matlab function doesn't change the data for selected arguments, either inadvertently or otherwise. Does anyone know of a nonburensome way to do this, or just as importantly, whether this is an unrealistic expectation?

I am using R2015b.

P.S. I've web searched and came across various relevant articles, e.g.:

http://www.mathworks.com/matlabcentral/answers/359410-is-it-possible-to-avoid-copy-on-write-behavior-in-functions-yet

http://blogs.mathworks.com/loren/2007/03/22/in-place-operations-on-data (which I need clarification on to fully understand, but it isn't my priority just now)

However, I don't believe that I am prematurely optimizing. I know that I don't want to modify the tables. I just need a way to enforce that without having to go through contortions like creating a wrapper class.

I've posted this at: * Stack Overflow * Google groups


Solution

  • There is no way of making variables constants in MATLAB, except by creating a class with a constant (and static?) member variable. But even then you can do:

    t = const_table_class.table;
    t(1,1) = 0; % Created and modified a copy!
    

    The reason that a function does not need to mark its inputs as const is because arguments are always passed by value. So a local modification does not modify data in the caller’s workspace. const is something that just doesn’t exist in the MATLAB language.

    On the other hand, you can be certain that your data will not be modified by any of the functions you call. Thus, as long as the function that owns the tables does not modify them, they will remain constant. Any function you pass these tables to, if they attempt to modify them, they will create a local copy to be modified. This is only locally a problem. The memory used up by this copy will be freed upon function exit. It will be a bug in the function, but not affect code outside this function.