matlab_newby
matlab_newby

Reputation: 79

How do I prompt the user to choose a file that will be loaded in matlab?

I want the user of a script I'm writing to be able to navigate to a file containing their data and to load the data into the workspace. For example, if a csv file contains two cells with the values 1 and 2 respectively, I want the user to simply choose this file and those two values will be assigned to a variable in the workspace.

I have looked at using:

filename = uigetfile('*.xlsx','*.csv')

But that just returns the name of the file. Perhaps I could construct a full path to where the file they choose is found, and then read it in that way (using xlsread or csvread) but I think I'm probably missing something here. It seems that there should be a more straightforward way of doing it.

Upvotes: 0

Views: 1661

Answers (1)

Vladislav Martin
Vladislav Martin

Reputation: 1674

I believe that you're looking for the uiopen() function. This function will:

Open dialog box for selecting files to load into workspace.

On default, this function will display in a file explorer dialog box with the filter set to all MATLAB® files (with file extensions *.m, *.mlx, *.mat, *.fig, *.mdl, and *.slx).

However, you can import data from data files like CSV files and spreadsheets as well. Simply select the (All Files) option for the Files of Type field.

Once you've selected the data file you're interested in, you will be prompted with another GUI object that previews the data you are about to load into MATLAB's workspace. If you're satisfied with the format of the variables presented in the preview, simply hit the green check-mark at the right-side of the tool-box ribbon in the GUI object and, huzzah, all of the data file's contents have been loaded into separate variables (named according to their respective headers).

Alternatively, though this is undeniably a longer-winded and uglier approach, if you'd like to use the filename returned from uigetfile('*.xlsx', '*.csv'), you could use the importdata() function. This will output a struct that contains each of the variables from your data file as a separate field:

[filename, pathname] = uigetfile( ...
    {'*.csv;', 'CSV file (*.csv)';
     '*.xlsx',  'Excel Spreadsheet file (*.xlsx)'; ...
     '*.*',  'All Files (*.*)'}, 'Pick a File to Import');
full_filename = fullfile(pathname, filename);
[A, delimiterOut] = importdata(full_filename);

Upvotes: 1

Related Questions