Cell Array of Function Handles Leaks Memory
Afficher commentaires plus anciens
I have a memory leak problem when I generate a cell array of functions in a for loop. An example would be like this:
for ii = 1:100000
[L1,L1str] = getSet(ii,ii+1)
end
If I run this code in Matlab R2013a, the memory use will increase until I am out of memory. Even when I clear all variables in the workspace, the memory used by matlab is not decreasing. Is this a known problem? If not, how do I solve it?
function [L1,L1str]=getSet(kl1x,kl1y)
kl1xstr = num2str(kl1x,32);
kl1ystr = num2str(kl1y,32);
L1str{1,1} = strcat('(sin((',kl1xstr,').*x).*exp(-1i.*(',kl1ystr,').*y))');
L1str{1,2} = strcat('((',kl1xstr,').*cos((',kl1xstr,').*x).*exp(-1i.*(',kl1ystr,').*y))');
L1str{1,3} = strcat('(-1i.*(',kl1ystr,').*sin((',kl1xstr,').*x).*exp(-1i.*(',kl1ystr,').*y))');
L1str{1,4} = strcat('(-(',kl1xstr,').^2.*sin((',kl1xstr,').*x).*exp(-1i.*(',kl1ystr,').*y))');
L1str{1,5} = strcat('(-(',kl1ystr,').^2.*sin((',kl1xstr,').*x).*exp(-1i.*(',kl1ystr,').*y))');
L1str{1,6} = strcat('(-1i.*(',kl1xstr,').*(',kl1ystr,').*cos((',kl1xstr,').*x).*exp(-1i.*(',kl1ystr,').*y))');
L1{1,1} = str2func(strcat('@(x,y)',L1str{1,1} ));
L1{1,2} = str2func(strcat('@(x,y)',L1str{1,2} ));
L1{1,3} = str2func(strcat('@(x,y)',L1str{1,3} ));
L1{1,4} = str2func(strcat('@(x,y)',L1str{1,4} ));
L1{1,5} = str2func(strcat('@(x,y)',L1str{1,5} ));
L1{1,6} = str2func(strcat('@(x,y)',L1str{1,6} ));
end
Réponse acceptée
Plus de réponses (1)
Philip Borghesani
le 22 Mai 2014
This function generates function handles that run faster in much less time and uses little memory overhead. I will also assert that it is much easier to read and maintain.
function [L1,L1str]=getSet(kl1x,kl1y)
function r=f1(x,y)
r=(sin(kl1x.*x).*exp(-1i.*kl1y.*y));
end
function r=f2(x,y)
r=(kl1x.*cos(kl1x.*x).*exp(-1i.*kl1y.*y));
end
function r=f3(x,y)
r=(-1i.*kl1y.*sin(kl1x.*x).*exp(-1i.*kl1y.*y));
end
function r=f4(x,y)
r=(-kl1x.^2.*sin(kl1x.*x).*exp(-1i.*kl1y.*y));
end
function r=f5(x,y)
r=(-kl1y.^2.*sin(kl1x.*x).*exp(-1i.*kl1y.*y));
end
function r=f6(x,y)
r=(-1i.*kl1x.*kl1y.*cos(kl1x.*x).*exp(-1i.*kl1y.*y));
end
L1{1,1} = @f1;
L1{1,2} = @f2;
L1{1,3} = @f3;
L1{1,4} = @f4;
L1{1,5} = @f5;
L1{1,6} = @f6;
end
James gave a good explanation of the cause of the problem. This is one more reason why avoiding eval and str2fun which is just a glorified eval is a good best practice.
Catégories
En savoir plus sur Function Creation dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!