Skip to content

Instantly share code, notes, and snippets.

@novelistparty
Last active August 29, 2015 14:20
Show Gist options
  • Save novelistparty/dac5f9485cff3c045af7 to your computer and use it in GitHub Desktop.
Save novelistparty/dac5f9485cff3c045af7 to your computer and use it in GitHub Desktop.
Nested-function handles stored inside structures
function [modes] = compute_modes(Nmode,z,desc)
% COMPUTE_MODES example function to demonstrate nested-function handles
% John Boyle, April 2015
for jj = 1:Nmode
data(jj,:) = sin(2*pi*jj * z);
end
function plot_modes()
figure
for ii = 1:Nmode
subplot(Nmode,1,ii)
plot(z,data(ii,:))
if ii == 1; title(['Mode from ' desc]); end
end
end
modes.data = data;
modes.Nmode = Nmode;
modes.z = z;
modes.desc = desc;
modes.plot = @plot_modes;
end
% Using nested-function handles to simplify calling utility functions
% John Boyle, April 2015
z = linspace(0,1,200);
m1 = compute_modes(2,z,'Type 1');
m2 = compute_modes(5,z, 'Type 2');
m3 = compute_modes(8,z, 'Type 3');
% These function handles save the function namespace.
% The memory use won't show up in the variable size
m1.plot()
m2.plot()
m3.plot()
% Variable size without handle
% 5524
% 10324
% 18324
% Variable size with handle
% 5732
% 10532
% 18532
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment