In-place modification - doesn't work as expected
17 次查看(过去 30 天)
显示 更早的评论
Hi!
I am trying to figure out how to prevent matlab from copying a huge array I want to modify inside a function and thus trying to reproduce an old blogpost example for in-place modification https://blogs.mathworks.com/loren/2007/03/22/in-place-operations-on-data/. I run the code from the example with minor modifications, but get unexpected results - no matter what I do, when the array is modified inside a function, matlab allocates extra memory of the size of the array (presumably, to perform a deep copy).
n = 38*2^25;
x = randn(n,1);
% Call functions with either regular or in-place semantics.
%% Call a Regular Function with the Same Left-Hand Side
x = myfunc(x);
%% Call an In-place Function with the Same Left-Hand Side
x = myfuncIP(x);
%% Call a Regular Function with a Different Left-Hand Side
y = myfunc(x);
%% Call an In-place Function with Same Left-Hand Side
% Note: if we changed this next call to assign output to a new LHS, we get an error
x = myfuncIP(x);
%% Actually works without an error?!
z = myfuncIP(x);
function x = myfuncIP(x)
x = sin(2*x.^2+3*x+4);
function y = myfunc(x)
y = sin(2*x.^2+3*x+4);
(MATLAB 2019b)
So my questions are:
- Is the blogpost no longer valid?
- Is the only way to avoid deep copying is to create custom handle datatype and redifine all operations? If so, does anyone know how would that new datatype behave when combined with parfoor slicing (given i redefine subsasgn and subref)? And is there somewhere a commonly used class that achieves that purpose (i looked through to some File Exchange options, but they seem to rely on some memory hacking that cases my Matlab to crash)?
Thanks!
0 个评论
回答(1 个)
Yash Srivastava
2022-10-21
In my understanding you are looking for ways to avoid unnecessary deep copy of data to optimize memory usage.
MATLAB can apply memory optimizations under certain conditions. Please refer to the following documentation-
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!