makedirid.m 877 B

1234567891011121314151617181920212223242526272829303132333435
  1. function f = makedirid(x,num)
  2. % function f = makedirid(x,num)
  3. %
  4. % <x> is a path to a file or directory
  5. % <num> (optional) is the non-negative number of elements desired. default: 2.
  6. %
  7. % return a string with the last <num> elements of the path joined with '_'.
  8. % also, any occurrences of '-' and '.' are replaced with '_'.
  9. % this function is useful for constructing MATLAB-compatible function/script names.
  10. %
  11. % history:
  12. % - 2013/10/13 - also replace '.' with '_'
  13. % - 2013/08/18 - now, '-' is replaced with '_' (so that the result
  14. % can be a valid function name).
  15. %
  16. % example:
  17. % isequal(makedirid('/home/knk/dir1/file-test'),'dir1_file_test')
  18. % input
  19. if ~exist('num','var') || isempty(num)
  20. num = 2;
  21. end
  22. % do it
  23. f = '';
  24. for p=1:num
  25. f = ['_' stripfile(x,1) f];
  26. x = stripfile(x);
  27. end
  28. f = f(2:end);
  29. % replace - and . with _
  30. f = strrep(f,'-','_');
  31. f = strrep(f,'.','_');