GUI Save Data with Button

23 次查看(过去 30 天)
Heidi
Heidi 2016-5-20
Hi there! I've made a GUI with GUIDE that plots three real time signals, and the data is written to a *.dat file:
fid = fopen('data_file.dat','w');
fwrite(fid,data_stream,'int16');
But everytime I run the program it overwrites the *.dat file, and I want to be able to save the data once in a while with a Save button. But I can't figure out how to save as a new file. I want the user to be able to pick the file name and which folder the file is saved in. This is my attempt so far:
% --- Executes on button press in Savebutton.
function Savebutton_Callback(hObject, eventdata, handles)
% hObject handle to Savebutton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
fid = fopen('data_file.dat','r')
MyData = fread(fid,inf,'int16')
MyData = uiputfile('*.mat', 'Save Workspace As');
What am I doing wrong? And is there anyway I can reset the plots once the data is saved? Thanks in advance!

回答(1 个)

Image Analyst
Image Analyst 2016-5-20
Make sure you call fclose(). Then, the next time (or even the very first time), open the file with 'a' or 'at' option instead of 'w'. This will append data.
Here is a snippet to ask the user to give a filename:
% Get the name of the file that the user wants to save.
% Note, if you're saving an image you can use imsave() instead of uiputfile().
startingFolder = userpath % Or "pwd" or wherever you want.
defaultFileName = fullfile(startingFolder, '*.*');
[baseFileName, folder] = uiputfile(defaultFileName, 'Specify a file');
if baseFileName == 0
% User clicked the Cancel button.
return;
end
fullFileName = fullfile(folder, baseFileName)
  4 个评论
Heidi
Heidi 2016-5-22
I'm quite confused - sorry, please bare with me. I have tried to use your code, and the Dialog Box opens and I am able to write in the File Name edit box, but it doesn't save anything. There is no new file saved to my computer...
My problem is: When I run the script, the data is written to a file called "data_file.dat". How do I save the data from 'data_file.dat' to a new file, by the push of a button?
Image Analyst
Image Analyst 2016-5-22
That code just allows the user to specify a filename in some folder. You still have to do the actual saving with some function. There are many ways to save data to a file and I don't know which you want. For example you could use save(), fwrite(), fprintf(), dlmwrite(), csvwrite(), writetable(), etc. Which one do you want?

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Interactive Control and Callbacks 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by