function f = makedirid(x,num) <x> is a path to a file or directory <num> (optional) is the non-negative number of elements desired. default: 2. return a string with the last <num> elements of the path joined with '_'. also, any occurrences of '-' and '.' are replaced with '_'. this function is useful for constructing MATLAB-compatible function/script names. history: - 2013/10/13 - also replace '.' with '_' - 2013/08/18 - now, '-' is replaced with '_' (so that the result can be a valid function name). example: isequal(makedirid('/home/knk/dir1/file-test'),'dir1_file_test')
0001 function f = makedirid(x,num) 0002 0003 % function f = makedirid(x,num) 0004 % 0005 % <x> is a path to a file or directory 0006 % <num> (optional) is the non-negative number of elements desired. default: 2. 0007 % 0008 % return a string with the last <num> elements of the path joined with '_'. 0009 % also, any occurrences of '-' and '.' are replaced with '_'. 0010 % this function is useful for constructing MATLAB-compatible function/script names. 0011 % 0012 % history: 0013 % - 2013/10/13 - also replace '.' with '_' 0014 % - 2013/08/18 - now, '-' is replaced with '_' (so that the result 0015 % can be a valid function name). 0016 % 0017 % example: 0018 % isequal(makedirid('/home/knk/dir1/file-test'),'dir1_file_test') 0019 0020 % input 0021 if ~exist('num','var') || isempty(num) 0022 num = 2; 0023 end 0024 0025 % do it 0026 f = ''; 0027 for p=1:num 0028 f = ['_' stripfile(x,1) f]; 0029 x = stripfile(x); 0030 end 0031 f = f(2:end); 0032 0033 % replace - and . with _ 0034 f = strrep(f,'-','_'); 0035 f = strrep(f,'.','_');