Search code examples
matlabmatlab-guidematlab-gui

How to save some values from gui into a text file and load them elsewhere as a number?


I have 2 values from an edit box and I want to write them in a txt file when I press a push button

function Masaedit_Callback(hObject, eventdata, handles)
% hObject    handle to Masaedit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB

function Arias_Callback(hObject, eventdata, handles)
% hObject    handle to Arias (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


function pushbutton7_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA

 m=str2double(get(handles.Masaedit, 'string'));
  assignin('base','m',m)

  A=str2double(get(handles.Arias, 'string'));
  assignin('base','A',A)
  twovalues = fopen('twovalues.txt','w');
  fprintf(twovalues,'%6d\t%3d',m,A);
  fclose(twovalues);

But I want to save them as:

m=value;
A=value;

After the values are saved , I want to load the text file in a function like:

function xypr=twovalues (m,A)

CD=1;

load ('twovalues.txt',m,A)
ad=(-1/2)*((CD*A)/m);
end

But that it seems a little tricky and I don't know how should I do the conversion because for A,m = I need to load them as a string and for the result I should use something like str2double.


Solution

  • I actually made a quick youtube video in response to your question, so if you want to watch that you can(I go into more depth there, but it is meant to be a bit more general):

    https://youtu.be/GQtYAT36CZ4

    Otherwise, a short answer is that it depends on whether you need that data available outside of matlab or not. Your approach is mixing those two - generally you should either set it up to not be accessible outside of matlab using the save command (save('filename.mat', 'm', 'A') and load('filename.mat', 'm', 'A')) or write to a csv with column headers (use writetable and readtable with a table containing only your variables for example). Note that for the purposes of your answer, csv is a text format. Of course it is possible to use fprintf as you describe, but that is really the hardest way of doing it. I hope that helps!

    Edit: I note in your question that part of your issue is related to the string vs double nature of the text box. The method I suggest here would cut in after you convert to double. No method will get rid of that issue, unless you use a gui element which outputs as double.