MATLAB: Do in-place function calls not work with structures in MATLAB 7.6 (R2008a)

MATLAB

MATLAB offers an optimization that can prevent a copy of a varible that is passed to a function from being created if the function returns the same variable. This in known as an "in-place" function call and can be helpful when working with large data sets.
My issue is that my large data set is part of a structure and this seems to negate the in-place optimization.
I have the following code:
function inplaceTest
x = randn(2^24, 1);
tic;
x = f(x);
toc;
data.x = x;
tic;
data = fData(data);
toc;
end
function x = f(x)
x(50) = 1;
end
function data = fData(data)
data.x(50) = 1;
end
When I execute 'inplaceTest' I get the following:
>> inplaceTest
Elapsed time is 0.001587 seconds.
Elapsed time is 0.160606 seconds.
>>
The call to the function 'fdata' takes longer to execute than the call to the function 'f' because a copy of the input data is being created.

Best Answer

This is not a problem with the inplace optimization, it is just MATLAB's expected copy-on-write behavior.
The line data.x = x causes data.x to hold a shared copy of x. The assignment 'data.x(50) = 1' needs to make a deep copy of data.x so that x doesn't get changed. You get the same behavior if you create the indexed assignment to data.x(50) outside of a function.
You can test this by modifing the function inplaceTest to read:
function inplaceTest
x = randn(2^24, 1);
tic;
x = f(x);
toc;
data.x = x;
tic;
data.x(20) = 20;
toc;
end
If you want to avoid the copy altogether, you need to make sure that data.x holds the only copy of the array (i.e. clear x after assigning it to data.x).
You can test this code as well:
function inplaceTest
x = randn(2^24, 1);
tic;
x = f(x);
toc;
data.x = x;
clear x;
tic;
data.x(20) = 20;
toc;
end