How do I split the file path into just a file name? Matlab GUI
조회 수: 96 (최근 30일)
이전 댓글 표시
I'm making a checkbox that's supposed to take a filepath from a listbox created and it needs to reduce the string seen in the listbox down to just the file name. Now the more complicated side of this is that it needs to do this for multiple strings. So let's say I import 3 files into the listbox, it needs to cut down the entire directory path into just the file name. When the box is unchecked, it should be able to bring back the original full path name in the box.
Any suggestions? It's been driving me nuts
댓글 수: 0
채택된 답변
Jan
2018년 5월 9일
편집: Jan
2018년 5월 9일
I have no idea what "When the box is unchecked" means. Listboxes cannot be checked or unchecked. I guess you have a listbox with file names and a check box to show or hide the paths.
See doc fileparts.
File = 'C:\Your\Folder\Name.txt'
[fPath, fName, fExt] = fileparts(File);
% fPath = C:\Your\Folder
% fName = Name
% fExt = .txt
Maybe you want:
FileExt = [fName, fExt]
Please clarify, what "file name" means exactly: With or without extension?
Now you want to hide or show the file path on demand?
FileList = {'C:\Your\Folder\Name.txt', ...
'D:\Another\Folder\Name2.dum', ...
'E:\Where\Ever\Name3.hello'};
% Store this list persistently, e.g. in the UserData of the edit field:
set(handles.edit1, 'UserData', FileList);
% Alternatively:
% handles.FileList = FileList;
% guidata(hObject, handles);
You need a helper function, because fileparts does not accept cell strings yet (blame MathWorks):
function [fPath, fName, fExt] = SuperFileParts(List)
if iscellstr(List)
fPath = cell(size(List));
fName = cell(size(List));
fExt = cell(size(List));
for k = 1:numel(List)
[fPath{k}, fName{k}, fExt{k}] = fileparts(List{k});
end
elseif ischar(List)
[fPath, fName, fExt] = fileparts(List);
else
error('Input not handled.')
end
end
Now in the callback of the checkbox:
function CheckboxCallback(objectH, EventData, handles)
if objectH.Value
handles.edit1.String = handles.edit1.UserData;
else
handles.edit1.String = SuperFileParts(handles.edit1.UserData);
end
end
댓글 수: 3
Jan
2018년 5월 9일
Please do not mix the terms "listbox", "checkbox" and "button". You "uncheck the checkbox" and "When the button is checked" - confusing.
If you need the filename with the extension:
function [fPath, fName] = SuperFileParts(List)
if iscellstr(List)
fPath = cell(size(List));
fName = cell(size(List));
for k = 1:numel(List)
[fPath{k}, name, ext] = fileparts(List{k});
fName{k} = [name, ext];
end
elseif ischar(List)
[fPath, name, ext] = fileparts(List);
fName = [name, ext];
else
error('Input not handled.')
end
end
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 File Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!