Note that there are some explanatory texts on larger screens.

plurals
  1. POMatlab function handle workspace shenanigans
    primarykey
    data
    text
    <p><strong>In short</strong>: is there an elegant way to restrict the scope of anonymous functions, or is Matlab broken in this example?</p> <p>I have a function that creates a function handle to be used in a pipe network solver. It takes as input a Network state which includes information about the pipes and their connections (or edges and vertices if you must), constructs a large string which will return a large matrix when in function form and "evals" that string to create the handle.</p> <pre><code>function [Jv,...] = getPipeEquations(Network) ... %// some stuff happens here Jv_str = ['[listConnected(~endNodes,:)',... ' .* areaPipes(~endNodes,:);\n',... anotherLongString,']']; Jv_str = sprintf(Jv_str); %// This makes debugging the string easier eval(['Jv = @(v,f,rho)', Jv_str, ';']); </code></pre> <p>This function works as intended, but whenever I need to save later data structures that contain this function handle, it requires a <strong>ridiculous</strong> amount of memory (150MB) - coincidentally about as much as the entire Matlab workspace at the time of this function's creation (~150MB). The variables that this function handle requires from the getPipeEquations workspace are not particularly large, but what's even crazier is that when I examine the function handle:</p> <pre><code>&gt;&gt; f = functions(Network.jacobianFun) f = function: [1x8323 char] type: 'anonymous' file: '...\pkg\+adv\+pipe\getPipeEquations.m' workspace: {2x1 cell} </code></pre> <p>...the workspace field contains everything that getPipeEquations had (which, incidentally is <em>not</em> the entire Matlab workspace).</p> <p>If I instead move the eval statement to a sub-function in an attempt to force the scope, the handle will save much more compactly (~1MB):</p> <pre><code>function Jv = getJacobianHandle(Jv_str,listConnected,areaPipes,endNodes,D,L,g,dz) eval(['Jv = @(v,f,rho)', Jv_str, ';']); </code></pre> <p>Is this expected behavior? Is there a more elegant way to restrict the scope of this anonymous function?</p> <p><em>As an addendum, when I run the simulation that includes this function several times, clearing workspaces becomes painfully slow, which may or may not be related to Matlab's handling of the function and its workspace.</em></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload