이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
Finding file in a before selected folder
조회 수: 8 (최근 30일)
이전 댓글 표시
Debbie Oomen
2018년 4월 13일
Hello everyone! I am new to GUI in MATLAB and I need to write an analysis user interface. I am just starting out and the first step for the GUI is to let the user select the directory that contains the data files. This is the code so far:
% % --- Executes on button press in ChooseFolder.
function ChooseFolder_Callback(hObject, eventdata, handles)
% hObject handle to ChooseFolder (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
folder = uigetdir('Search Folder Containing Data Files');
if isequal (folder, 0);
set(handles.DisplayFolderName, 'String', 'No folder selected');
set(handles.FileInputString, 'enable', 'off');
else
[~, name] = fileparts(folder);
textLabel = sprintf('Selected folder is %s', name);
set(handles.DisplayFolderName, 'String', textLabel);
filePattern = fullfile(folder, '*.csv');
allfiles = dir(filePattern);
for k = 1 : length(allfiles);
baseFileName = allfiles(k).name;
end
end
Now I want to add a Edit Text and Push Button. The Edit Text allows the user to enter the filename (for example): ID0123. Then, the Push Button can be pressed and MATLAB will look for this file in the before chosen directory. I have tried this:
% --- Executes on button press in findfile1.
function findfile1_Callback(hObject, eventdata, handles)
% hObject handle to findfile1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
filename = get(handles.edit1, 'String');
if exist (name, filename)
csvread(filename);
else
warningMessage = sprintf ('Warning: file does not exist:\n%s' , filename);
uiwait(msgbox(warningMessage));
end
But this does not do anything. Can anyone please help me with this issue?
Would be very much appreciated
댓글 수: 2
Rik
2018년 4월 16일
Another probable cause of problems is that the ChooseFolder callback doesn't seem to store all information in the guidata handle struct.
And why did you close this question?
Debbie Oomen
2018년 4월 16일
How can I store the information in the guidata handle struct?
I honestly did not know what it did. I thought nobody was reading this question anymore so that is why I closed it and posted it again. My mistake.
채택된 답변
Stephen23
2018년 4월 13일
편집: Stephen23
2018년 4월 13일
I looked at the exist help, but could not find any syntax that matches how you are using it. Probably you should read the documentation and use one of the supported syntaxes, e.g.:
if 2==exist(filename,'file')
Also the line:
csvread(filename);
reads some data and then discards it immediately.
댓글 수: 21
Stephen23
2018년 4월 16일
"does this mean that I cannot analyze anything with this filename then?"
It is not clear what you mean. If you have a valid filename then you can open it (assuming that you have permission, etc). The fact that you used incorrect syntax for exist tells us nothing about the filename, or what you can use it for.
Debbie Oomen
2018년 4월 16일
Well, I want the user of the program to be able to search for the wanted file and then let matlab do analyses on this file. You mentioned that csvread(filename) means that it reads some data and then immediately discards it. Does this also work if the filename is in this form: ID0123? I keep on getting this error:
Error using exist The first input to exist must be a string scalar or character vector
Stephen23
2018년 4월 16일
편집: Stephen23
2018년 4월 16일
"You mentioned that csvread(filename) means that it reads some data and then immediately discards it. "
Because you did not allocate the output to any variable and also suppressed the output using the ; the data get imported and then immediately discarded. If you want to import the data into the MATLAB workspace to work on then you will need to allocate the output to a variable, e.g.:
M = csvread(...);
How to call functions and get their outputs is explained in the introductory tutorials:
"I keep on getting this error:"
Error using exist The first input to exist must be a string scalar or character vector
Read the error message: did you check if the first input argument is char vector or string? Is it? I can't check this because I am not sitting in front of your laptop, and I don't have all of your data. But you can read the error message, and check what the first input argument is. This is the first step to debugging your own code.
In my answer I showed you one way of using exist: as you have not shown any new code I have no idea if you have changed your code to a supported syntax or not. Please make a new comment and show the code that you are using now.
"Does this also work if the filename is in this form: ID0123?"
Sure, I don't see any reason why not. I just tried it myself by creating a file named ID0123.txt (attached to this comment) and then running this code:
>> exist('ID0123.txt','file')
ans = 2
>> M = csvread('ID0123.txt')
M =
1 4 7
2 5 8
3 6 9
It worked just as the exist and csvread documentation states that it should.
Debbie Oomen
2018년 4월 16일
% --- Executes on button press in findfile1.
function findfile1_Callback(hObject, eventdata, handles)
% hObject handle to findfile1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
filename = get(handles.edit1, 'String');
if 2 == exist (filename, 'file')
csvread(filename);
else
warningMessage = sprintf ('Warning: file does not exist:\n%s' , filename);
uiwait(msgbox(warningMessage));
end
I thought that get(handles.edit1, 'String'); is a char vector or string? Sorry but I am relatively new to this all. Thanks for the help!
Stephen23
2018년 4월 16일
편집: Stephen23
2018년 4월 16일
"I thought that get(handles.edit1, 'String'); is a char vector or string?"
I presume that you are using uicontrol, in which case the 'String' property can be a "character vector | cell array of character vectors | string array | pipe-delimited row vector":
Not all of these are accepted as inputs for exist. For that reason you can easily check it yourself, either by setting a breakpoint and using debugging mode, or by adding a few commands, e.g.:
filename = get(handles.edit1, 'String');
class(filename)
size(filename)
Depending on the size and class you might be able to simply convert to character like this:
filename = get(handles.edit1, 'String');
filename = char(filename);
If there are multiple text lines it will not make sense to pass these all at once to exist.
Debbie Oomen
2018년 4월 16일
Okay awesome this seems to be working! I do not get the input error anymore. However, no matter if I choose an existing file, I keep on getting my error msgbox. Did I do something wrong when I specified the folder code? I only want Matlab to look for the csv files in that specific folder:
function ChooseFolder_Callback(hObject, eventdata, handles)
% hObject handle to ChooseFolder (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
folder = uigetdir('Search Folder Containing Data Files');
if isequal (folder, 0);
set(handles.DisplayFolderName, 'String', 'No folder selected');
set(handles.FileInputString, 'enable', 'off');
else
[~, name] = fileparts(folder);
textLabel = sprintf('Selected folder is %s', name);
set(handles.DisplayFolderName, 'String', textLabel);
filePattern = fullfile(folder, '*.csv');
allfiles = dir(filePattern);
for k = 1 : length(allfiles);
baseFileName = allfiles(k).name;
end
end
Stephen23
2018년 4월 16일
편집: Stephen23
2018년 4월 16일
@Debbie Oomen: I suspect that you need to provide the full filename (i.e. including the path to the folder where the file is) when you call exist:
if 2 == exist(fullfile(folder,filename), 'file')
ChooseFolder_Callback looks okay, although it is not clear what purpose the loop has, as it doesn't appear to be used for anything so far.
Debbie Oomen
2018년 4월 16일
Then I get the error that folder is an unknown variable. Do I need to add another uigetdir for the edit1 part of the gui then?
Stephen23
2018년 4월 16일
편집: Stephen23
2018년 4월 16일
"Do I need to add another uigetdir for the edit1 part of the gui then?"
You do not "need" to do that... but you could if you wanted to: you are the GUI designer, and so how your GUI works is your decision. If the user has already selected the folder using another callback then surely you could just use that folder? Isn't that the idea? You will need to pass the data (i.e. folder name) from the "folder" callback to the "file reading" callback using guidata or your preferred method. See:
If you do not have experience sharing data between callbacks then I recommend that you read those pages very carefully, and try some of the examples. Do not use global variables.
Debbie Oomen
2018년 4월 16일
편집: Stephen23
2018년 4월 16일
Based on those pages I have tried adding the following to my Choose Folder callback:
guidata = h0bject.handles
Then, in the findfile callback i added:
get(handles.ChooseFolder)
I still end up with the same result..
Debbie Oomen
2018년 4월 16일
Now, I tried this code:
% handles structure with handles and user data (see GUIDATA)
ChooseFolder_Callback(h0bject.ChooseFolder, eventdata,handles);
filePattern = fullfile(foldername, '*.csv');
allfiles = dir(filePattern);
for k = 1 : length(allfiles);
baseFileName = allfiles(k).name
end
filename = get(handles.edit1, 'String');
filename = char(filename);
if 2 == exist(fullfile(foldername,filename), 'file')
F= csvread(filename);
else
warningMessage = sprintf ('Warning: file does not exist:\n%s' , filename);
uiwait(msgbox(warningMessage));
end
However, when I run the code, I need to select the folder again while I've already done it in a previous callback. How can I just get the code to find the files in the corresponding folder?
Stephen23
2018년 4월 16일
편집: Stephen23
2018년 4월 16일
@Debbie Oomen: guidata is a function, not a variable, and it has two syntaxes shown in the guidata help. You need to use those syntaxes. Add the folder to the handles structure and then save it using guidata at the end of the ChooseFolder_Callback, something like this:
handles.folder = folder;
guidata(hObject,handles)
In the findfile1_Callback you should then be able to access
handles.folder
Debbie Oomen
2018년 4월 16일
I still get an error @Stephen Cobeldick This is the code now:
% --- Executes on button press in ChooseFolder.
function ChooseFolder_Callback(hObject, eventdata, handles)
% hObject handle to ChooseFolder (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
foldername = uigetdir('Search Folder Containing Data Files');
if isequal (foldername, 0);
set(handles.DisplayFolderName, 'String', 'No folder selected');
set(handles.edit1, 'enable', 'off');
set(handles.findfile1, 'enable', 'off');
else
[~, name] = fileparts(foldername);
textLabel = sprintf('Selected folder is %s', name);
set(handles.DisplayFolderName, 'String', textLabel);
end
handles.foldername = foldername;
guidata(hObject,handles)
function edit1_Callback(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in findfile1.
function findfile1_Callback(hObject, eventdata, handles)
% hObject handle to findfile1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.foldername;
filename = get(handles.edit1, 'String');
filename = char(filename);
if 2 == exist(fullfile(foldername,filename), 'file')
F= csvread(filename);
else
warningMessage = sprintf ('Warning: file does not exist:\n%s' , filename);
uiwait(msgbox(warningMessage));
end
Debbie Oomen
2018년 4월 16일
And this is the error:
ans =
'/Users/debbieoomen/Desktop/Data Files'
Undefined function or variable 'foldername'.
Error in whatever>findfile1_Callback (line 181)
if 2 == exist(fullfile(foldername,filename), 'file')
Error in gui_mainfcn (line 95)
feval(varargin{:});
Error in whatever (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in
matlab.graphics.internal.figfile.FigFile/read>@(hObject,eventdata)whatever('findfile1_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating UIControl Callback.
Stephen23
2018년 4월 16일
편집: Stephen23
2018년 4월 16일
Just like when you called csvread without any output argument, this line does not allocate its data to any variable, so it temporarily creates a variable and then discards it immediately:
handles.foldername;
If you want to use the foldername variable then it first has be allocated some data: so far you have not defined it to be anything. One option would be to use the values from your other callback:
foldername = handles.foldername;
or alternatively simply use the handles.foldername field directly inside fullfile:
if 2 == exist(fullfile(handles.foldername,filename), 'file')
Debbie Oomen
2018년 4월 16일
Final question and then you'll be rid of me (for now), the user now has to enter the total file name (including extension), is it possible to only enter the name of the file without extension? I already tried
[~,name] = fileparts(filename)
but this does not seem to work
dpb
2018년 4월 16일
Well, if the file has an extension it has to be included somehow...if your user is selecting the file through a GUI such as UIGETFILE, it will return all the information on an existing file you need; if you're making them type in a name then "yes, virginia, you do need an extension" if it's to match an existing file that has one--that's a rude way to make an interface work, however...
fileparts only separates out pieces of an existing filename and returns those; it doesn't make anything out of thin air.
Debbie Oomen
2018년 4월 16일
Okay, but I have found some information on using dir(*.*) for finding a file with a specific letter or letters in it. That way, the user could just type in the first few letters and number of the file and matlab finds it in the folder. I just cannot seem to figure out where it belong in my GUI code and if it would even work?
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Help and Support에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom(English)
아시아 태평양
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)
