Memory gestion with object properties as inputs of a function

1 view (last 30 days)
Hello,
I wonder what is the gestion of the function inputs with Matlab. In my mind, inputs were not copied by a function when they were not modified in it.
Nevertheless, in the (stupid) example below it seems that it is not the case :
1. I create an object (handle type) with some data and a 'test' method calling the interp1 function :
classdef TestObject < handle
properties
data = [sort(randn(1,1000000));randn(19,1000000)];
end
methods
function a = test(obj,x)
a = interp1(obj.data(1,:),obj.data(2:end,:)',x);
end
end
end
2. Then I call the 'test' method from an external script : % script test for TestObject clc clear all clear classes
obj = TestObject();
profile on
for x=0:0.1:1
var = obj.test(x);
end
profile viewer
In my mind, in the 'test' method, 'data' are not supposed to be copied when passed to the interp1 function (which does not modify them). Nevertheless, when I have a look in the profiler, the self-time (built-ins, overhead, etc.) of the test method represents 75.5% of the total (4.440 s vs 1.440 s for the interp1 function)... so I am quite confident that the inputs are copied.... Right ?
Any idea/suggestion/help ? If it is the case, any suggestion (not for this stupid example, but a more general way to avoid this problem) ?

Accepted Answer

Walter Roberson
Walter Roberson on 10 Jun 2011
When you create a subsection of an array, MATLAB has to copy the data. MATLAB does not copy the data if the entire array is being passed.
  3 Comments
Walter Roberson
Walter Roberson on 15 Jun 2011
I do not see any reason why interp1 could not be used in what you show, provided there is enough memory, and provided you are meeting any real-time targets.
People who have analyzed interp1's performance say that it is very efficient; it would be difficult to code alternatives that were as fast.
You may wish to investigate Bruno's MATLAB File Exchange contribution for inplace pointers, http://www.mathworks.com/matlabcentral/fileexchange/24576-inplacearray-a-semi-pointer-package-for-matlab
James Tursa
James Tursa on 25 Jan 2018
Another option that was just posted to the FEX for getting shared data copies of contiguous sub-sections of an existing variable:
Although this would not help the particular case noted above since row data is not contiguous. It could be used if the the data was reorganized in memory as columns though.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!