a b/util/export_fig/copyfig.m
1
function fh = copyfig(fh)
2
%COPYFIG Create a copy of a figure, without changing the figure
3
%
4
% Examples:
5
%   fh_new = copyfig(fh_old)
6
%
7
% This function will create a copy of a figure, but not change the figure,
8
% as copyobj sometimes does, e.g. by changing legends.
9
%
10
% IN:
11
%    fh_old - The handle of the figure to be copied. Default: gcf.
12
%
13
% OUT:
14
%    fh_new - The handle of the created figure.
15
16
% Copyright (C) Oliver Woodford 2012
17
18
% 26/02/15: If temp dir is not writable, use the dest folder for temp
19
%           destination files (Javier Paredes)
20
% 15/04/15: Suppress warnings during copyobj (Dun Kirk comment on FEX page 2013-10-02)
21
22
    % Set the default
23
    if nargin == 0
24
        fh = gcf;
25
    end
26
    % Is there a legend?
27
    if isempty(findall(fh, 'Type', 'axes', 'Tag', 'legend'))
28
        % Safe to copy using copyobj
29
        oldWarn = warning('off'); %#ok<WNOFF>  %Suppress warnings during copyobj (Dun Kirk comment on FEX page 2013-10-02)
30
        fh = copyobj(fh, 0);
31
        warning(oldWarn);
32
    else
33
        % copyobj will change the figure, so save and then load it instead
34
        tmp_nam = [tempname '.fig'];
35
        try
36
            % Ensure that the temp dir is writable (Javier Paredes 26/2/15)
37
            fid = fopen(tmp_nam,'w');
38
            fwrite(fid,1);
39
            fclose(fid);
40
            delete(tmp_nam);  % cleanup
41
        catch
42
            % Temp dir is not writable, so use the current folder
43
            [dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
44
            fpath = pwd;
45
            tmp_nam = fullfile(fpath,[fname fext]);
46
        end
47
        hgsave(fh, tmp_nam);
48
        fh = hgload(tmp_nam);
49
        delete(tmp_nam);
50
    end
51
end