MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1
c = onCleanup(@()fclose(fid));

s = fread(fid);
.
.
.
end

Example 2 — Maintain the Selected Folder

This example preserves the current folder whether functionThatMayError returns an
error or not:

function changeFolderSafely(fileName)
currentFolder = pwd;
c = onCleanup(@()cd(currentFolder));

functionThatMayError;
end % c executes cd(currentFolder) here.

Example 3 — Close Figure and Restore MATLAB Path

This example extends the MATLAB path to include files in the toolbox\images folders, and
then displays a figure from one of these folders. After the figure displays, the cleanup
routine restore_env closes the figure and restores the path to its original state.

function showImageOutsidePath(imageFile)
fig1 = figure;
imgpath = genpath([matlabroot '\toolbox\images']);

% Define the cleanup routine.
cleanupObj = onCleanup(@()restore_env(fig1, imgpath));

% Modify the path to gain access to the image file,
% and display the image.
addpath(imgpath);
rgb = imread(imageFile);
fprintf('\n Opening the figure %s\n', imageFile);
image(rgb);
pause(2);

% This is the cleanup routine.
function restore_env(fighandle, newpath)
disp ' Closing the figure'
close(fighandle);

26 Error Handling

Free download pdf