Clear Filters
Clear Filters

Export to Excel from MATLAB GUIDE GUI (user defines filename and directory)

1 view (last 30 days)
I'm trying to export data saved from a Simulink simulation to Excel using 'xlswrite'. I have used the following code to export data to Excel successfully:
evalString = 'xlswrite(''vehicle_Data'',x_data,''Sheet 1'',''A1'')';
evalin('base', evalString)
However, each time I click the export button in my GUI, it overwrites the previous Excel file. Ideally, I would like the user to be prompted to enter a filename and location after clicking the export button within my GUI. I'm also aware of uiputfile which I've attempted to use, however each time I try to export the data, an error occurs:
Undefined function or variable 'x_data'.
Please see my code below which overwrites each time. Even if i could get the code to rename the file each time, that would work as long as I can access previous exported simulation data.
% --- Executes on button press in export_data.
function export_data_Callback(hObject, eventdata, handles)
% hObject handle to export_data (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%x
evalString = 'xlswrite(''vehicle_Data'',x_data,''Sheet 1'',''A1'')';
evalin('base', evalString)
%y
evalString = 'xlswrite(''vehicle_Data'',y_data,''Sheet 2'',''A1'')';
evalin('base', evalString)
%accel
evalString = 'xlswrite(''vehicle_Data'',accel_data,''Sheet 3'',''A1'')';
evalin('base', evalString)
%Velocity
evalString = 'xlswrite(''vehicle_Data'',velocity_data,''Sheet 4'',''A1'')';
evalin('base', evalString)
I hope you can help!

Answers (1)

Dennis
Dennis on 30 Aug 2018
Every function has its own workspace. Your function does not know x_data, y_data, accel_data and velocity_data. There are several ways to pass variables between callbacks and for more details about this topic please read this article ( link).
It seems that your are working with GUIDE, so you could append your variables to your handles structure. I am missing the part of your code were your variables origin from, it could look like this:
function MyDataCreation(hObject,event,handles)
handles.x_data=1:3;
handles.y_data=4:6;
handles.accel_data=7:9;
handles.velocity_data=10:12;
guidata(hObject,handles)
end
In your export function:
function export_data_callback(hObj, event, handles)
handles=guidata(hObj);
%now you can use handles.x_data, handles.y_data ...
%rest of your code
%
end
You can either use uiputfile or inputdlg to ask for a filename.
As soon as you have your variables in your function there is no need to use evalin anymore.

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products


Release

R2016a

Community Treasure Hunt

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

Start Hunting!