In-place modification - doesn't work as expected

조회 수: 17 (최근 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 CenterFile Exchange에서 Whos에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by