GUI Save Data with Button

23 views (last 30 days)
Heidi
Heidi on 20 May 2016
Commented: Image Analyst on 22 May 2016
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!

Answers (1)

Image Analyst
Image Analyst on 20 May 2016
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 Comments
Heidi
Heidi on 22 May 2016
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 on 22 May 2016
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?

Sign in to comment.

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!