In-place modification - doesn't work as expected

12 ビュー (過去 30 日間)
Vasily K
Vasily K 2022 年 10 月 17 日
回答済み: Yash Srivastava 2022 年 10 月 21 日
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!

回答 (1 件)

Yash Srivastava
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-

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by