uifile.m 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. function [varargout] = uifile(mode, varargin)
  2. %UIFILE Standard get/put dir/file dialog box which remembers last used folder
  3. % UIFILE is a wrapper for Matlab's UI{GET/PUT}{DIR/FILE} functions with the
  4. % ability to remember the last folder opened. Only successful file
  5. % selections update the folder remembered.
  6. %
  7. % This version saves the last path infomation in system wide temporary folder.
  8. %
  9. % Usage:
  10. % [...] = uifile('get', ...);
  11. % [...] = uifile('put', ...);
  12. % [...] = uifile('getdir', ...);
  13. % The rest of input and output arguments are the same as MATLAB built-ins.
  14. %
  15. % This work is a combination of Chris Cannell's uigetfile2 functions.
  16. %
  17. % See also UIGETFILE2, UIGETDIR, UIGETFILE, UIPUTFILE.
  18. %
  19. % Written by: Xiaohu Mo
  20. % xiaohumo@gmail.com
  21. % Argument checking
  22. if nargin < 1
  23. warning('Usage: uifile(''getfile'', ...)');
  24. return;
  25. end
  26. % Name of mat file to save last used directory information
  27. lastDirMat = fullfile(tempdir, '_matlabLastUsedDir.mat');
  28. % Try load the saved path and set the dir to use
  29. % default useDir is current path
  30. useDir = pwd;
  31. if exist(lastDirMat, 'file')
  32. % lastDirMat mat file exists, load it
  33. load('-mat', lastDirMat)
  34. % check if lastDir variable exists and contains a valid path
  35. if exist('lastDir', 'var') && exist(lastDir, 'dir')
  36. % set default dialog open directory
  37. useDir = lastDir;
  38. end
  39. end
  40. % Save the pwd, cd to useDir, open dialog and change back
  41. savedPwd = pwd;
  42. cd(useDir);
  43. % Call uiget/putfile with arguments passed in
  44. switch lower(mode)
  45. case 'get'
  46. [varargout{1} varargout{2} varargout{3}] = uigetfile(varargin{1:end});
  47. case 'put'
  48. [varargout{1} varargout{2} varargout{3}] = uiputfile(varargin{1:end});
  49. case 'getdir'
  50. [varargout{1}] = uigetdir('', varargin{1:end});
  51. end
  52. cd(savedPwd);
  53. % If the user did not cancel the file dialog then update lastDirMat
  54. if ~isequal(varargout{1}, 0)
  55. try
  56. % save last folder used to lastDirMat mat file
  57. switch lower(mode)
  58. case 'get'
  59. lastDir = varargout{2};
  60. case 'put'
  61. lastDir = varargout{2};
  62. case 'getdir'
  63. lastDir = varargout{1};
  64. end
  65. save(lastDirMat, 'lastDir');
  66. catch
  67. % error saving lastDirMat mat file
  68. % display warning, the folder will not be remembered
  69. disp(['Warning: Could not save file ''', lastDirMat, '''']);
  70. end
  71. end