tags:

views:

45

answers:

1

A have a struct with four very large matrices that corresponds to grayscale images. Depending on the input of my function, I want to store one of those four matrices in a variable. However, since those matrices are very large, I don't want to create a copy of them.

Is there something similar in Matlab to the concept of reference in C++? Or in other words: is it possible to have two variables pointing to the same matrix?

+7  A: 

Matlab uses a "lazy copy on write" for variables. That means that if you pass your array (or all of them) to your function, they won't be duplicated unless you write into the array(s). In other words, you may not need to do what you want to do.

For example, if you store your images in a structure imgStruct with fields firstImage to fourthImage, and you pass e.g. imgStruct.fourthImage as input to the function, the array is not duplicated, even if it is called e.g. inputImage inside the function.

If you plan to write to the image, you can create a handle class to store your image data, which is passed by reference (thus, if you modify the image inside the function, it is also modified in your base workspace).

Jonas
@Jonas: Excellent answer. Couldn't find documentation so I deleted my answer. Also, I heard the same at a seminar held by MATLAB in my university so I knew passing large variables would not be a problem.
Jacob
for a detailed example of what happens behind the scene (copy-on-write), refer to this post: http://stackoverflow.com/questions/1735841/initializing-a-ublas-vector-from-a-c-array/1735997#1735997
Amro

related questions