Alternative to using global for a very large array

6 Ansichten (letzte 30 Tage)
Hesham
Hesham am 16 Sep. 2019
Kommentiert: Hesham am 17 Sep. 2019
Hi
I have a quite large array of data (100s of MB) that I am using as a LUT in multiple functions. If I declare it as a parameter, it will be copied locally by each function, which is an unjustified waste of memory. The solution I am currently using is to define it as global. I know that globals are highly discouraged, but is there a smarter alternative for my case?
  1 Kommentar
Bruno Luong
Bruno Luong am 17 Sep. 2019
Bearbeitet: Bruno Luong am 17 Sep. 2019
As per isakson explained to you, you try to FIX something that does not exists and hurt your code.
MATLAB does not copy the matrix if you call it as parameter, or even assign it to new variable
BIG = rand(1e4);
B = BIG;
C = foo(BIG);
function C = foo(A)
C = A;
end
A, B, C use a shared-memory of data.
So remove this global and program normally as you would and let MATLAB does the work.
NOTE: However if you do this there is 2 big matrices in memory after the third statement
BIG = rand(1e4);
B = BIG;
B(1) = 10;

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

per isakson
per isakson am 17 Sep. 2019
Bearbeitet: per isakson am 17 Sep. 2019
"unjustified waste of memory" Matlab is smarter than that, see Avoid Unnecessary Copies of Data.
If LUT is look-up-table and the called function doesn't change the LUT-value no copies are made.
See also Memory Management for Functions and Variables. This blog is more that ten years and Matlab evolves, but it's worth reading.

Weitere Antworten (0)

Produkte


Version

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by