File Exchange Pick of the Week

Video series: Reading Excel data into MATLAB with a GUI 143

Posted by Doug Hull,

I had a chance to work with a MATLAB user that was interested in bringing her Excel data into MATLAB and plotting different variables. This was a fairly standard file format, just columns of data. It was pretty easy to read in the data with XLSREAD:

Note that three minutes into the video above, I use a neat cell mode trick that many might not know about.

Once this was done, it was time to turn that script into a function so that it could be reused easily.

Finally, the function needed a GUI to make it easy to view any piece of data from the file.

143 CommentsOldest to Newest

Hello,

the “Build a GUI” video is quite helpful.
For further videos, I propose to use a larger Matlab window (in particular width). Then I can see the whole line and do not have to switch to the source code.

Thanks

Gerd,

I completely agree that it would be nice to see the entire command line. The trade-off I am struggling with is I can only make the screen so wide if I want to embed the video in a web page. I could zoom out, but then the text is illegible.

I will try to use …
short commands or …
the commands can be …
continued like this …
so they all fit on …
screen at once.

If anyone has any other ideas, please let me know. I can make the videos taller and fit in the blog, but 500 pixels wide is all that fits nicely here (that is still 180 more across than I could get on YouTube)

Thanks,
Doug

Great videos Doug!

I got a problem when reproducing the Excel-plotting GUI… I guess I am missing something so the outcoming GUI stands by itself fine.

Here is what it happened:

While I was running the GUI from GUIDE or its M-file, everything was ok. When I opened MATLAB again (during a new session) and clicked the .FIG file on the Current Directory Window, the GUI appeared, but it started to produce the following errors:

—————–
handles =

fileName: ‘070924bgzFake.xls’

??? Reference to non-existent field ‘popupmenuX’.

Error in ==> PlotExcelGUI>pushbuttonLoadXLS_Callback at 140
setPopupmenuString(handles.popupmenuX, eventdata, handles)

Error in ==> gui_mainfcn at 95
feval(varargin{:});

Error in ==> PlotExcelGUI at 42
gui_mainfcn(gui_State, varargin{:});

??? Error using ==> PlotExcelGUI(‘pushbuttonLoadXLS_Callback’,gcbo,[],guidata(gcbo))
Reference to non-existent field ‘popupmenuX’.

??? Error while evaluating uicontrol Callback

—————–

How can I make the .FIG file to run my GUI without getting into GUIDE each time?

Thanks. And again, great job for those videos!

Mauricio

I tried downloading the mainGui.fig, mainGui.m and the excel file so I can run it, and the gui came up just fine, but once I selected the excel file, I got some callback errors:

?? Reference to non-existent field ‘popupmenuX’.
Error in ==> mainGui>pushbuttonLoadXLS_Callback at 130
setPopupmenuString(handles.popupmenuX, eventdata, handles)
Error in ==> gui_mainfcn at 75
feval(varargin{:});
Error in ==> mainGui at 42
gui_mainfcn(gui_State, varargin{:});
??? Error while evaluating uicontrol Callback.

Any ideas?

Mauricio and Richard,

To run this GUI, you should run the .m file, not the .fig file. The .m file contains a lot of important initialization code that should be run.

Doug

Hi Doug,
Thanks for the prompt replay. I’m gonna ping you on something that I’m having a great deal of difficulty with. And that is, I have a text file pretty much the same format as the excel example you have. The first row is the header row (string) that specifies the names for the columns (numbers). How can I adapt your code to my needs? My goal is to come up with the gui that gives you the option to pick and choose which columns go to x and y, just like you have in your example. I think the key difference is knowing what ‘xlsread’ actually does. I’m using ‘textread’, but the real problem is the first row is a string, which ‘textread’ won’t read in. I can get ‘textread’ to read in the first column strings, but then I’ll need a separate ‘textread’ to read in the rest of the numbered data. Do you see how it complicates things?

Thanks,
Richard

Hi

Thanks a lot to you Doug Hull, I have learned a lot about MATLAB specially GUI by your video.

I am from very distance area but I am very interested in MATLAB.

In few words I am a big fan of yours

thanks again

FFA

[minor typos corrected, Doug]

Hi
Thank you very much for your videos, I am a final year electrical engineering student and your videos have helped me produce MATLAB code that will be really useful in compleating my final year project.

many thanks
Trevor

Hi,
I have a similar question about importing excel data into matlab, but about a more complicated type of file. My excel files has a lot of text near the top, and then many columns of data with x-y-z locations for 3-D points. After ALL of this data, there’s some more text, and then EMG data. I want to write a function to read through past the text, find the columns of data I’m interested in, and store them in their own variables. Do you know how I would go about doing this?

Maryam,

This is getting into reading custom formats inside of an Excel file. MATLAB gives you the ability to read an arbitrary range inside of an Excel file, and the ability to parse those results. These are the low level functions that are need to accomplish this goal. There is no built-in function that will do what you want since files can vary so much. However, you should be able to build your own.

Doug

Is this code will face problems if it used in matlab 6.5 ? because that happen to me
I mean the code used to read from excel files ..

Thanks

I want to know if it is possible to write data into an excel files using GUI Matlab program ??
Right now I am going to develop a big program that takes data from first users and make several kinds of calc as an output … excel file it is suppose to store these results (by Matlab supervision of course)… and for other users it is should to review latest results , makes same calc and then makes it is Owen results in different excel files …..
Is there any advice U can give me here?

Farasha,

I developed this code in 2007a. I just tried it in MATLAB 6.5, but it seems that XLSREAD was improved since then and this code does not work in 6.5.

For your second question, yes, you can write out Excel files. This functionality has been introduced since 6.5. You will likely want to upgrade to take advantage of these new features.

Doug

Hi,

My question is can i run an m file from excel sheet? i know i can read data from excel sheet and do calculations in matlab and then return the data to the excel sheet but this requires running of the m file. I am in the process of developing a userfriendly software and i feel combination of excel with VB will be more fit for the purpose. Please do reply.

regards
sivapriya

I am trying to plot data in 3D. I have degrees for axis 1 across the top, degrees for axis 2 down the side, and the data (which will be the Z-axis) are what is in the matrix. How do I modify the mainGUI to incorporate x,y, and z and recognize that there isn’t a “heading” for the column 1 since that is actually one of the axis and not the data itself.

Thanks,
Jason

Jason,

This is quite a bit different from the GUI that I have here. I think you would be best served to start a new one with the knowledge you have gained in making this one.

I am not sure I understand the last part of your question. You might be better served by asking this of tech-support:

http://www.mathworks.com/support

Doug

Dear Doug,
I would like to merge data files from a few .xls files in one .mat file. Since in .xls file the max no. of column is 256 but I need 600 columns for my input data. That’s why I split data in few .xls files. I know that I can do it by cut and paste the data in .mat file but it will be time consuming. Is there any other way to do it? Please help. Thanks

regards,
Izzri

Izzri,

You can read in from several files and then concat the variables together:

a = **read file**
b = **read file**

c = [a b];

Enjoy,
Doug

Dear Doug Hull,
Hi!
I have seen your tutorials and I have to admit that I have learned a lot thanks to your efforts.
While watching the tutorials I noticed that there aren’t any which covers the table component to be used as UI in order to collect and save editable data in a file in order to eliminate the dependency of Excel. I have tried to search for a hint but failed to find any which helps. I wonder if you are kind enough to show likes of me a hint on how to save editable data from a table to a file and then load it back to the table.
Respect,
Hamid

Doug,

I have no trouble reading in files, manipulating the data and plotting. My trouble is I want to do this with quite a few data files.

Is there a way to run through all the files in a folder or directory without inputting the file names manually? Can you help me automate this process?

A.K.A.
1) I want to open a file in a folder
2) Read the data into MATLAB*
3) Manipulate it *
4) Open the next file in the folder and repeat

Hi Doug, thanks for your video about reading an Excel file from Matlab. I am pretty new to Matlab but I have been presented with a project to work on that I think Matlab will help with.

I have an Excel sheet with a lot of data that I need to make searchable for specific user-defined values. (I was thinking of putting in some user prompts). It seems like xlsread reads the entire Excel file, or a range of cells in the file. For my purposes I will only need to read one or a few cells at a time. Then I need to load a DLL for a data analysis program I have (I was thinking about using the Matlab Generic DLL Interface), and call specific functions to operate on the data, and then I was thinking about using xlswrite to print the results to a new worksheet or to the next page within the same Excel file.

For example, I run the program and I happen to be interested in Temperatures between 95 and 100. So I search for all of these values that might be in the Excel file, then let’s say I have a function in my DLL file called TEMP2. I would call that function and use it to process these temperatures.

Do you think I am on the right track? Could you possibly help me figure out how I can accomplish this?

Thank you.

Thanks Scott, I will probably send you an email.

Basically what’s hard for me is wading through the syntax when first starting out, it’s not obvious to me what certains commands do unless I can see an example of where it is used.

I am pretty good at adapting examples to my specific problem.

The main concerns I have is that the DLLs I have won’t be compatible with the Matlab DLL Interface and I’ll end up using a Fortran script (which is originally what the data software people recommend, but what do they know about Matlab?)

Hi Doug,
Following your fantastic tutorial, I try to create a GUI bringing my Excel data and doing some calculations. My excel file has 20 worksheets(20 subjects), and each worksheet has data. These are part of my code:

setPopupmenuString(handles.popupmenu1, eventdata, handles)

function setPopupmenuString(hObject, eventdata, handles)
fileName = handles.fileName;
[tpe, xlSheets] = xlsfinfo(fileName);
set(hObject, ‘string’, xlSheets);

It updates all sheet names on popup menu. Then I want it automatically updates data when I select different name from popup menu. So my question is how to get data from each sheet? I tried “get(handles.popupmenu1, ‘value’)” but it doesn’t work.
Any help will be highly appreciated! Thanks.

Henry,

It is not clear to me the specific question you need answered. I think you have a pop-up menu that is correctly populated with the various sheet names from your Excel file. From there, you want to figure out the name of the sheet that was selected in the pop-up.

Value will give you an ordinal number. You need to then use this number to index into the cell array that is stored in the ‘string’ property to get the actual string that represents the sheet name.

Doug

hi,
I have a question
I have a matlab code and i want to read a data from SQL server database to use it in that code

so i want to know if i can read this data? if yes, how can I do this ?

Best Regards,
Maram

I have several data files which contain some parameter like
distance and speed and each file might have different parameters and i do not include these parameters as part of the name and so when i look at the folder that i have this data in all the files have is a sequential number as part of their name but i would like to have an excel sheet which takes in the file name and parametrs like distance and speed and so when i want to know what file has what parametrs i just open the excel sheet and keep it open while i’m looking at the data. I am not sure how i would go about keeping track of what position the new parameters from a different dataset would go on the excel sheet.
I.e say its the 5th file and i would like to put its name and a distance in the distance column and a speed in the speed column, do i have to load the excel file first to see what position(line on excel sheet) i need to put the new parameters in and tehn i would have to write it to the array and reload that array to the file. Is there an easier method of doing this? Any help would be appreciated.
thanks

Hussein,

If I understand your question, you have a directory of files like this:

1.xls
2.xls
3.xls
list.xls

The numbered files have some data that represents variables, we will call them alpha and beta.

you want list to be of this form:

list.xls
fileName | alpha | beta
1.xls | 0.1 | 1.1
2.xls | 0.2 | 2.2
3.xls | 0.3 | 3.3

I think you could do something like the following:

Make a function
[fileName, alpha, beta] = getFileInfo(fileName)

This will give you the data you need to place in the list.xls

Where does the data go in the list.xls file?

Well, if you do a
fileList = dir(‘*.xls’);

You will get a list of files in an array of structures. The array number for each member of the structure can be used to determine the row of list.xls to use.

You could just generate the whole .xls each time you need it bly getting the directory as mentioned above and totally remaking list.xls.

If I understand your question, this should give you some ideas.

Let me know how this goes.
Doug

I have a 100MB size text dataset starting like follows. How can I read this file in Matlab easily as it showing file is too large. I would like to do fft analysis and statistical analysis of the data too. Thanks, Niaz

IMC FAMOS
Name: c_acc
Time: 26.11.08 17:42:08
Length: 842751
Unit X-Axis: 2e-005 s
1st x-Value: 0 s
Unit Y-Axis: m/s^2
Data:
0 1.052799
0.00002 0.885308
0.00004 0.191418
0.00006 -0.370872
0.00008 -0.394799
0.0001 -0.107673
0.00012 0.107673
0.00014 0.095709
0.00016 -0.047854
0.00018 -0.155527
0.0002 -0.071782
0.00022 0.239272
0.00024 0.574254
0.00026 0.681926
0.00028 0.550327
0.0003 0.239272
0.00032 -0.167491
0.00034 -0.442654
0.00036 -0.358909
0.00038 -0.071782

Hi,
I would like to create a 3D figure with data from excel. I can create x along row 1, y along column 1 and the z’s will correspond to the respective (x,y). How do I import this data and capture x,y,z respectively?

Thanks,

Doug

what I need specifically is …

how do I import a matrix into matlab? In the excel sheet,
x values are in cells: A2:A30
y values are in cells: B1:X1
Z values are in cells: B2:X30

both mesh and surf require Z to be input as matrix and do not accept array input. Only plot3 does and I am not so keen on plot3

thanks,

Atripathy, for importing such a spreadsheet I would think this would work.

data = xlsread('YourSpreadsheet.xls'); %whatever
x = data(2:end,1); %Mx1
y = data(1,2:end); %1xN
Z = data(2:end,2:end); %MxN

For graphing you may need to do something like this.

[Y,X] = meshgrid(y,x); %MxN

Normally X comes before Y but you set them up opposite in your description, which could trip you up with dimension mismatch errors.

Does that help?

hi
i would like to know if there is a way to load all the sheets in a .xls file which have 2 specific values and get a plot of them.i need only the values at cells B36 and B6 but from every sheet.

for example sheet1:B36=5 B6=1
sheet2:B36=4 B6=3
i just need a plot of them.reading values from different sheets.
thanks

hi again
Ty a lot for the reply!
i need to ask something for xls files with matlab.
i used this code to load 10 sheets in a xls file but everytime i need to open the xls check the number of sheets and modify the code below. maybe there is a command or something to avoid open verytime my xls files to check the sheets?for example if i have 4 xls files i need everytime to open them check the number of sheets and modify the code which is kinda slow.there is other way to avoid this?

v=zeros(1,10);
n=size(v);
for x=1:10
v(x)=xlsread(‘time.xls’,x,’B38′);

Ty again
my regards

Hi, i would like to ask how can i import a set of data from excel to matlab, Fourier transform the data and use it to plot the amplitude against the number of data, N. I am new to Matlab, can you show me how can i code this? My excel contains only 2 set of data, 1 column for years and the other is the raw data for sunspot activity. I appreciate your help.

o…and the given formula is y[n]=x[n]-1/N ∑〖x[i]〗 where N=300, x[i] is the set of sunspot number and by taking the fourier transform of it then plot the amplitude against n not N. Thanks.

hi
i would like to convert a specific time like 01:03:55 which i load from an excel file to total seconds.

for example 01:03:55=3825seconds
maybe there is a way?

Theo, does this help?


>> 1*60^2+3*60+55
ans =
3835


>> (datenum('1:03:55')-datenum('0:0:0'))*24*60*60
ans =
3835

when i run this command i get this:

(datenum(‘0:01:55′)-datenum(‘0:0:0′))*24*60*60

ans =

115.0000
and for the previous i get this
(datenum(‘1:03:55′)-datenum(‘0:0:0′))*24*60*60

ans =

3.8350e+003

hmm maybe i do something wrong?

sorry for the late reply Doug, don’t quite understand how to import the file from excel to Matlab. Do i have to save the file in any particular folder 1st? I have follow all the steps but i still cannot read anything that is useful.When i evaluate the selection it gives me the value. How it become like this? My data consists only 2 column*300 row data.

hi
i have this real time values in a xls file
13:36:31
13:36:41
when i use xlsread for each time i get
0.5670 0.5671 and with the Datestr function i get these times
13:36:28=0.5670
13:36:37=0.5671 which is kinda strange, why matlab doesnt read exactly the contents of the xls file?

Sean,

The directory that the file in does not matter, as long as the file is on the path so that MATLAB can find it. Are you able to do the example from the movie?

-Doug

Theo,

It sounds like the cell might be formatted as time or date. What happens if it is changed to something else?

Doug

hi,
the truth is that i am working on excel with matlab and i facing some problems.for example i have 2 vectors full of elements,V and t(time).At the moment my program calculate the duration of the measurement(seconds) but i need every 6min=360sec to average the elements of vector V.Also i know that every value of vector V have 3 sec time interval.i used a loop like this but its only for 6min.

u=0;
for i=1:x
if u<360
u=u+vv; %vv=3sec
v1(i)=xlsread(‘time1.xls’,i,’B38′);%v1 is a vector storing my values until u<360

end
end
i need every 360 sec average the values of vector V in that time

my regards

Theo,

The problem is likely the format with which you’re displaying the date number.


format % use the default display format
y = datenum(0, 0, 0, 13, 36, 31)
datestr(0.5670, 'HH:MM:SS')
datestr(y, 'HH:MM:SS')
checkForEquality = y-0.5670

The datenum is displayed as 0.5670, but it’s not exactly 0.5670 — it’s:


format long g
y = datenum(0, 0, 0, 13, 36, 31)

In general, when trying to validate results, don’t type what MATLAB has displayed into a function call — instead, store the result in a variable and use that variable in the function call. This makes sure that you don’t lose any precision due to the display format you’re using not displaying all the decimal places.

Hi Doug,
Can you tell me how to calculate area under the curve in a plot, which is plotted using MATLAB.

Thanks
Ashish Singh

ashish,

The answer to your question depends on whether you have a function that you evaluated to generate the data for the plot, or if you just have a set of data that you plotted. If you have a function, then use QUAD or QUADGK as Doug suggested. If you just have a set of data, use TRAPZ or CUMTRAPZ instead.


% Generate some sample data
x = 0:0.1:pi;
f = @sin;
y = f(x);

% using QUAD:
integral1 = quad(f, 0, pi);
% using TRAPZ:
integral2 = trapz(x, y);

% Compare the two answers
difference = integral1 - integral2

To get the two answers to agree more closely, you could change the tolerance in the QUAD call and/or sample the function more frequently in the data you pass to TRAPZ.

I found your demonstration very helpful on how to read Excel into Matlab. From Excel I’m trying to plot two different data sets against time. One data set is an order of magnitude bigger than the other so I would like to use two y axes to show both data sets on the same graph.

Best wishes,

Robert

@Robert,

Thank you for the kind words. I think you will be interested in the MATLAB fuction

PLOTYY

This will help you with your task.

Doug

@Robert,

Thank you for the kind words. I think you will be interested in the MATLAB function

PLOTYY

This will help you with your task.

Doug

Hi Doug,

Can you help me how to load a MAT file in a GUI?

For example, if I have a MAT file called test2 I can load it using

load test2.mat

If the test2.mat file contains 50 files, I can extract all the data of the file #1 using the following:

d=dataset(1);
d=load(fullfile(d.pathname, d.filename));

But this time I created a GUI and into the M-code of the GUI I’m trying to do the same in the Opening Function because I want to load the data at the beginning but I’m getting an error because it does not recognize the structure d.pathname

I appreciate your help !!

@tony,

I am not sure I understand your question. I am not sure how a .mat file can contain 50 files.

In the above code, the second line overwrites the value of d with load. If that is what you want, it is OK. This may be why your d.pathname structure is being unrecognized. Set some breakpoints there and confirm that d is what you think it is.

Doug

Doug,

Sorry if I didn’t explain well my problem. I’m analyzing bearing data and I have a MAT file that contains 984 files saved in a structure called dataset. Therefore, if I want to analyze the data from file #5 for example, in a normal M-code I just need to do the following:

load test2.mat % the name of the MAT file is test2

d=dataset(5);
d=load(fullfile(d.pathname, d.filename));

Then d contains all the data that correspond to the file #5. But now I have a GUI and in the M-code I’m trying to load the same MAT file in order to analyze the data and I couldn’t. I just want to extract all the data files from the MAT file. I hope this helps

Thank you very much

Tony Silva

Tony,

When you say the .MAT file has 984 files, you mean it has the *names* of the files.

So the real problem is that you have data in a callback in a GUI, and you are not able to pass said data to another function inside the same GUI. The fact that it came from a file originally is not particularly important.

I think that this video on GETAPPDATA and SETAPPDATA should be of interest to you.
http://blogs.mathworks.com/videos/2005/10/03/guide-video-part-two/

Depending on what you are doing with the data, and the file sizes, you might be better off just loading the data from file inside of any given callback when needed.

Doug

make sure beforing writing xlsread(‘filename’) syntax, that the file exists in the current diretory, otherwise prompt out warning ,like ??? Error using==>xlsread File not found.

@Kirsten,

What part are you talking about? How to read in a another column, or how to use another input to scatter (or scatter3)

Doug

Hello Doug,

Great tutorial i’m studying engineering and trying to write a cylinder pressure combustion analysis program, I have a slight problem and I’m pretty amateur with matlab everything works fine until I run the program with the call back line to update the axis. My call back in the push button is slightly different than yours please see below.

set(handles.popupmenuy,’callback’,’Cylinder_Pressure_Analysis_GUI(”updateAxes”,hObject,eventdata,guidata(hObject))’)

I get the following error message which isn’t very helpful to an amateur

??? Undefined function or variable ‘hObject’.

??? Error while evaluating uicontrol Callback

your help would be greatly aprreciated – Thanks Luke

hi this is the problem i am facing … wen i try to read file from the xls sheet
error i am gettin in matlab :
>> filename = ‘ testwork.xls';
>> a = xlsread(filename);
Warning: Could not start Excel server for import, ‘basic’ mode will be used. Refer to HELP
XLSREAD for more information.
> In xlsread at 176
??? Error using ==> xlsread at 219
XLSREAD unable to open file testwork.xls.
File /Users/neo/Documents/MATLAB/ testwork.xls not found.

Hi, Doug,

I know that in the workspace, we can directly input excel files and save them by column. But if the columns are not of equal length, you will have a lot of NaN in your vectors. How should I deal with it? It’s not so easy to get rid of these NaNs.

Thanks a lot!

Jade

Jade,

Matrices in MATLAB cannot contain “jagged” edges — all rows must have the same number of columns and vice versa. If you want to operate on all your data at once, leave it in matrix form with the NaNs included and use ISNAN to detect the NaN values as you’re working with an entire row or column. If you want to split the data part into columns ahead of time, you will need to store them in a cell array, as the individual cells in a cell array can be of different sizes, shapes, or data types.

C = cell(1, 3);
C{1} = ones(1, 4, 'single');
C{2} = rand(3, 3);
C{3} = 'File Exchange Pick of the Week';
C
% Extract the 3-by-3 random matrix into a variable
y = C{2}

Dear Doug,

I’m using Matlab 2009b, the callback from the push button is very different from yours as seen in the video , instead of

mainGui(‘pushbuttonloadxls’,gcbo,[],guidata(gcbo))

the call back appears to be

fitting(‘pushbuttonloadxls_Callback’,hObject,eventdata,guidata(hObject))

from the property inspector, when I copied this call back to the command I, errors occur, saying

??? Undefined function or variable ‘hObject’.

??? Error while evaluating uicontrol Callback

I wonder what is wrong,

please advise.

Hi,

I have problem regarding Gui. When I click on Load.xls, the columns names for x and y axis did not appear on gui, but I can see olumn names on the command window. This is strange. I am using the following gui commands as you mentioned in the vedio.

and the command window error is:

mainGui>pushbuttonLoadXLS_Callback at 130
setPopupString(handles.popupmenuX,eventdata, handles)

Error in ==> gui_mainfcn at 96
feval(varargin{:});

Error in ==> mainGui at 42
gui_mainfcn(gui_State, varargin{:});

??? Error while evaluating uicontrol Callback>

hi Doug I using matlab R2006a, can I read data from an excel 2007 to GUI matlab,
are they same method/sintaks like read from excel 2003?

then I have 3 figure file (1 figure is main menu & 2 figure are main menu function) who all of those figure I want to make a stand alone application .exe. All figure can change to exe files & 2 main menu function succes when I run the exe files but problem that I found is when I run the main menu exe files to call one of main menu function there are an error message.
How I can clear this problem??

Much appreciated, Doug. These videos were quite easy to follow, a testament to your solid instruction. Thank you for providing this wonderful service!

Hi Doug,

I’ve figured out how to import data from excel and plotting them. I have 2 columns (dates and some prices). The dates will not be incremental (exclude Saturday, Sundays, bank holidays etc).

How do I plot the prices (y-axis) against the dates (x-axis)? When I import the dates and returns using xlsread:

[returns, dates]=xlsread(‘test.xls’);

The dates are given an type ‘cell’ which means i cant plot it. This is regardless of how I format the ‘dates’ in excel i.e. either dd.mm.yyyy or yyyymmdd (i can always play around in excel to change the formatting)

I have looked everywhere on this website and was wondering if you can help shine some light on this.

Thanks in advance,
Syaza

Dear Doug,
Great videos. I have the same exact problem as Luke (January 15th, 2010), namely when i update the axes with the following lines

set(handles.popupmenuX,’callback’,’MainGUI(”updateAxes”,hObject,eventdata,guidata(hObject))’)
set(handles.popupmenuY,’callback’,’MainGUI(”updateAxes”,hObject,eventdata,guidata(hObject))’)

I get back

??? Undefined function or variable ‘hObject’.
??? Error while evaluating uicontrol Callback

I was able to not get an error by adding @(hObject,eventdata) in front of mainGUI by reading the help section but it still does not plot and I do not get what is going on here. Please Help!
Thanks,
Chris R.

Dear Doug,
Great videos. I have the same exact problem as Luke (January 15th, 2010), namely when i update the axes with the following lines

set(handles.popupmenuX,'callback','MainGUI(''updateAxes'',hObject,eventdata,guidata(hObject))')
set(handles.popupmenuY,'callback','MainGUI(''updateAxes'',hObject,eventdata,guidata(hObject))')

I get back

??? Undefined function or variable ‘hObject’.
??? Error while evaluating uicontrol Callback

I was able to not get an error by adding @(hObject,eventdata) in front of mainGUI by reading the help section but it still does not plot and I do not get what is going on here. Please Help!

Thanks,

Chris R.

@Christopher,

Can you do this from within GUIDE property inspector rather than at the script level? I suspect you are running into scoping issues.

Doug

Doug,
I am not sure I understand your response. How can I change the callback from within the GUIDE property inspector, it appears it is read only. I am not sure what you mean by scoping issues, but I the callbacks that invoke updateAxes are at the end of the pushbuttonLoadXLS_callback function.
Thank you so much,
Chris

Ok,
so regarding my previous posts, I never figured out how it is supposed to work, but you can get around this problem by copy the meat inside the update axes function and pasting it directly into the pushbutton, popupmenuX, and popupmenuY callback files. So anytime you touch anything, it plots. Less elegant, but hey I have deadlines.
Cheers!

@Christopher,

Sometimes expediency wins!

I just checked, it is not read only for me.

Doug

Hey Doug
I have the same problem as Luke and Christ
??? Undefined function or variable ‘hObject’.
??? Error while evaluating uicontrol Callback

How should I fix it? I am using Matlab R2010a

Pls help
Saurabh

Hello Doug

Thanks for your reply…
I am able to solve the problem by writing the context (Code) in Callbacks of the popup menus. So everything is working alright.. But I was not able to do it as in the videos..may be some problem with MATLAB version..

My problem was similar like “Christopher R replied on May 20th, 2010 at 03:56 UTC :” and Elly replied on February 28th, 2010 at 22:12 UTC :

But I can share files and all if you like
Anyways many thanks for the videos.
Saurabh

Hi Doug,

I am using ANSYS and obtain my data in a text file. I need to use a formula on one of the columns (B-field) and convert every value. I have no experience with programming. How do I do this using MATLAB?

My text file would look like this:

NODE BX BY BZ BSUM
1 -0.89476E-04-0.25646E-03 0.0000 0.27162E-03
2 -0.29235E-02-0.14783E-03 0.0000 0.29273E-02
42 -0.77138E-03-0.11299E-02 0.0000 0.13681E-02
I just need the node number and BX column.

Thank you for your help.

Hi Doug,

I need to development an application based on GUI for my master thesis. So what do i need is:
I have a popupmenu with several option that can be selected (but only one will) and i need, for each option selected, read some data from one excel file and then fill some edit text with the data loaded from the excel file. how do i do this ?? I need some help.

Thank you for your help.

@Ricardo,

What have you tried, and what is your specific question?
Is it the popup menu (uicontextmenu ???), filling the editbox, loading the excel data?

Doug

ok I try to be more explicit.

when I click on an option from the popupmenu I whant to read the data associated to that option from the excel file and then put that information (data) in editboxes. So, my dificulty is read data from the excel file when i click on an option from popupmenu and then fill the editboxes with that information. I do not know how to do it. I already have the popupmenu and the several option.

sorry for my english and thanks for your help.

@Doug – Thank you for your reply. I have tried dlmread and GUI import of data in Matlab. However, the data columns in my text file have no delimiters. That is why I cannot isolate one of the columns to apply a formula to them and convert it. The text file obtained from ANSYS looks like this:
S BX
0.0000 0.55300E-02
0.75000E-05-0.48924E-02
0.15000E-04 0.39459E-02
0.22500E-04-0.27902E-02
0.30000E-04-0.15254E-02

My goal is to write a program that imports this file into MATLAB, isolates the BX data column, applies a formula to convert into force data and then plots the field.

@sgalawal,

Space is considered a delimeter. Once you have imported the data, then manipulate it. Without more information, I am going to say you are better off importing all the data first then throwing away what you do not need.

I notice that there is no space between the “-05-0.48″ This complicates things greatly. Is that a transcription error or is that how the file is?

doug

hello sir , i saw this video and trying to made the same but i am also getting the same error as all others please help me.

error is :

Error in ==> readxls1>pushbuttonloadXLS_Callback at 84
setPopupmenustring(handles.popupmenuX,eventdata, handles)

Error in ==> gui_mainfcn at 96
feval(varargin{:});

Error in ==> readxls1 at 42
gui_mainfcn(gui_State, varargin{:});

Error in ==>
guidemfile>@(hObject,eventdata)readxls1(‘pushbuttonloadXLS_Callback’,hObject,eventdata,guidata(hObject))

Hi Doug,

I have a follow up problem with the loading of excel data. I have got data that is always in the same format, although it varies in length. So I want to read the columns to a variable row length. Is there any smart way to do this? I tried googling but there is nothing I can find.

Kind regards

Harm Kooiker

Doug:

I have imported some excel data using the GUI method outlined in the video. I want to know how to overlay multiple graphs on the same axis for comparison. How would I go about doing this using the GUI method.
Thanks

@Aaron,

If I understand the question correctly, you will want to use HOLD ON. That will do the trick.

Doug

Hey Doug…this is excellent. However, when I try to download the files associated with these videos, I get an error on the file exchange. I tried looking for these files in the file exchange, but could not find them. The earliest files by you in the file exchange are from Nov 2007. Is there any way I can still get access to these files?

I originally wrote my code similar to this one in matlab 6.5 and moved it to a computer with matlab 7.4 on it. When selecting a file it would up date a listbox so it was possible for users to graph multiple plots at once. The problem is that since I moved it the plot on the gui does not update (or graph at all). I narrowed the problem down to this line of code as everything else works properly:

set(handles.listbox, ‘callback’, ‘maingui(”updateAxes”, gcbo,[],guidata(gcbo))’)

how would I change this to have it work in matlab 7.4 (R2007A)?

Thanks

@Amy,

Without more context, I am not sure, but I think you should look at the autogenerated callbacks (look in property inspector) and then model the string on that. this is likely similar to how you discovered that string in the first place.

Doug

I did get that string from the Callbacks in the property inspector (pretty much straight from the 3rd video) and that line of code worked perfectly in matlab 6.4 but when moving the code over to 7.5 it no longer works. It doesn’t give an error, but doesn’t ever enter the ‘updateAxes’ function either.

Is there another way to make the plot update everytime the columns are changed?

I would like to know about how to convert a mat file into excel file. I have normalized a data set which is in excel sheet converted to mat file then normalized. But trying to view it in excel sheet pls help me sir…

Regards,
Kishore

Hi,

I want to read an Excel file from Matlab.
But the problem is that first I have to omit some rows of the excel file as below:
My excel file is a large file upto 150 Mb.
Every 1024 rows comes 4 rows of header which I would like to delete using Matlab. Then I will read them from Matlab.

xxxx xxx xxx
xxxx xxx xxx
xxxx xxx xxx
xxxx xxx xxx
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5

1024 1024 1024
xxxx xxx xxx
xxxx xxx xxx
xxxx xxx xxx
xxxx xxx xxx
1 1 1
2 2 3

@Reza,

XLS read lets you choose which range to read in. Also, you could post process to remove them if you just read the whole thing in.

Doug

Hello,

I have a problem in Matlab with a GUI and function xlsread:
I developed a graphical interface that allows to read and draw the Excel files in matlab,

here is the program:

Select the button:

Code :
function Select_button_Callback(hObject, eventdata, handles)
global A f; % A: matrice de fichier Excel, f : la page de classeur
file_Name = uigetfile(‘*.xls’); % pour choisir les fichiers Excel
A=xlsread(file_Name,f);
set(handles.editfileName,’string’,file_Name)
guidata(hObject,handles)

Edit text: To enter the page of the Excel file
Code :
function f_Callback(hObject, eventdata, handles)
h=findobj(gcf,’Tag’,’f’);
f=str2double(get(h,’string’));

The Process button: to plot the function plot
Code :
function pushbutton3_Callback(hObject, eventdata, handles)
figure(2);
global A;
plot(A(:,1),A(:,6))

but in the end I still have the same problem (xlsread function considers the variable f as a character ‘string’ and if I change f by an integer, eg 28 or 3 function xlsreal it works well, but I want to change from outside ie from the GUI.

matlab error message:

Code:
Code :
Error using ==> xlsread at 130
Sheet argument must be a string or an integer.

Error in ==> prog_updata_excel>Select_button_Callback at 91
A=xlsread(file_Name,f);

Error in ==> gui_mainfcn at 96
feval(varargin{:});

Error in ==> prog_updata_excel at 42
gui_mainfcn(gui_State, varargin{:});

Error in ==>
@(hObject,eventdata)prog_updata_excel(‘Select_button_Callback’,hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback

I’m stuck for 4 days. Please I need your help. Thank you

hie Doug,
I have a problem. For the excel files i imported into the GUI, I only have 2 columns name frequency and accelerator. However, at my popupmenu there, it only appear to have frequency there. Others is a long list of blank list and at the end, got a number there. Can i know what is my problem?How can i solved it?
thanks
Regards,
Ean

Hi there,

I have a project currently working on at the moment in matlab, here is the problem, im trying to use xlsread command in matlab to read an xls file saved in my workspace, not just that alone, i want matlab to read a specific column and rows not just all of them.. does anybody have any ideas how to do that?

Thanks

Hi can anyone tell me how to unlock the readonly excel file using matlab. When I copy a read only file from one directory to other it works but the status of destination file will be read only. This occurs in matlab 7.9 not in matlab 6.5.

Please help me on this…

I want to show the datas from excel file in a table, but of any file, so i dont have the numbers of the rows and columns.
Can you help me?

I would like to download the mainGui.fig, mainGui.m and the excel file which are used in your tutorial.Could you please tell me the way?

I have a n*3 (n rows and 3 columns) matrix and I want to save or convert that matrix into a excel file.Could you please help me out?

-Thanks

i want to read binary numbers from excel file and convert it into decimal number in matlab…. Kindly please help me out

and also read sheet from excel which contains in first column floating decimal and floating binary number and in 2nd column it contains the conversion type i.e

10011.11 10
232387.2489 2
101111.010 10
.
.
.
.

first read this data and then convert it to the type specified in 2nd column of excel sheet.
kindly help me out

Hello,
I need to analyze some data for a experiment. So, I read some data(from .txt file) into matlab GUI and plotted a figure in logarithm scale. How can I return the data from Matlab GUI/m file into the excel sheet? Could you please help me?

Thanks
D Bhuiyan

The example does not appear to work in 7.12.0.0635

There are a number of comments starting in Jan. 2010 mentioning that that this demonstation is running into a problem with callback. Several comments later suggest the same thing.

This demonstation should first be removed and then re-recorded in a later version. Having a non-working example does not benefit anyone.

If you are new to MatLab, do not waste your time trying to replicate this demo as the final step of implimenting the call back will not work.

hi Doug,
i found so interesting your videos but i got some problems while using your techniques. here are : ??? Error using ==> xlsread at 219
XLSREAD unable to open file DataD2.xls.
File C:\Program Files\MATLAB\R2010b\bin\DataD2.xls not found.
what should i do?

Mady

I have some problem… for the first column of my excel file is a txt… lets say this is the out out after i insert the following command:

>> fileName=’Fruit Population.xlsx’

fileName =

Fruit Population.xlsx

>> [numbers,colNames]=xlsread(fileName);
>> colNames

colNames =

Columns 1 through 2

‘Municipalities’ ‘Mango’
‘Boston’ ”
‘Cateel’ ”
‘Baganga’ ”
‘Caraga’ ”
‘Manay’ ”
‘Taragona’ ”
‘Banaybanay’ ”
‘Lupon’ ”
‘San Isidro’ ”
‘Gov Generoso’ ”
‘Mati’ ”

Columns 3 through 4

‘Sugar Apple’ ‘Star Fruit’
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”

Columns 5 through 6

‘Star Apple’ ‘Durian’
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”

Columns 7 through 8

‘Soursop’ ‘Cucumber Tree’
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”

Columns 9 through 10

‘Jackfruit’ ‘Lanzones’
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”

Columns 11 through 12

‘Mountain Apple’ ‘Mangosteen’
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”

Columns 13 through 14

‘Pineapple’ ‘Rambutan’
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”

Columns 15 through 16

‘Bried fruit’ ‘Tamarind’
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”

Columns 17 through 18

‘Pomelo’ ‘Coconut’
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”

Columns 19 through 20

‘Lolly Fruit’ ‘Banana’
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”
” ”

hello,
I have a java interface that has 2 drop downs for year and for month. i have JAVA-MATLAB connectivity created using JMatlink. now, i want the year and month selected on java interface to be passed to a .m file for fetching data from excel into matlab. Using engEvalString() i could open the same .m file where year & month is to be passed. i am stuck, so as how to pass selected year & month to this .m file.

please help. this is related to my project. i cant proceed further without getting the solution over this.

Hi doug i’m trying to read a xls file. I can do it using “xlsread” but the cell with decimal numbers in the xls file contains NaN values. How i can do to read the correct value?
Thank you!

I have a time column is Excel ( format is string )..something like this..
11: 20: 10: 010000
11: 20: 10: 030000
11: 20: 10: 050000
11: 20: 10: 070000
11: 20: 10: 090000
11: 20: 10: 110000
11: 20: 10: 130000

When i read with Xlsread The time coulumn i am getting as string . How can I make it on the X axis of the plot .Please help

I want to draw a bar graph of activity done in one hour. But i have to consider seconds which means that 60*60= 3600 values along x-axis. I want to know how can i do this in one graph?

Secondly, i have a value of a col which is around 20 (max), but all the other values are in thousand, even some values go beyond 10 thousand, so i need to print the smaller value on top of the each bar.

Any help or pointer will highly be appreciated

Greeting!!!
I want to make a project in which there is data in the form of strings.So using MATLAB I want do have following features:
1.User will upload the Excel file and will tell the column which he wants to plot.
2.To calculate the frequency of data in particularly selected column
3.Than plot the graph
4.Do some calculation through coding in MATLAB
5.The output after calculation will be some portion of graph which will be presented in front of user,automatically h juste only have to load excel file and tell the column.
Till now I planned all these features to be in my project,more have to be explored.

Now my Query is that I tried out Your video tutorials and can easily imported the excel file but following problem is occurring:
1.In the column choice all the text are shown instead of just particular,may be this is due to the fact that my excel file contain string data instead of numeric
2.I even tried to make the separate spreadsheet which has S.no and already calculated frequency of data(all numeric) of concerned column but when I try do upload the Excel after running your taught file made than that particular file is not in the list to choose.Is there any requirement of Size of file to get open in GUI format in MATLAB
3.I even add that frequency calculation in separate sheet in the original file but than there is not a feature to select the sheet along with file name as in the video.
I am new to MATLAB programming
Please do give suggestion to make my project with mentioned features,more user-friendly and is there is any new features I can add..
Kavita

While running the following gui code i got this error : Undefined function or variable ‘hObject’. Error while evaluating uicontrol Callback.
Please help me out.
Thanks
Code Start from below:

function varargout = faltu(varargin)
% FALTU MATLAB code for faltu.fig
% FALTU, by itself, creates a new FALTU or raises the existing
% singleton*.
%
% H = FALTU returns the handle to a new FALTU or the handle to
% the existing singleton*.
%
% FALTU(‘CALLBACK’,hObject,eventData,handles,…) calls the local
% function named CALLBACK in FALTU.M with the given input arguments.
%
% FALTU(‘Property’,’Value’,…) creates a new FALTU or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before faltu_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to faltu_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE’s Tools menu. Choose “GUI allows only one
% instance to run (singleton)”.
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help faltu

% Last Modified by GUIDE v2.5 04-Nov-2012 10:59:37

% Begin initialization code – DO NOT EDIT
gui_Singleton = 1;
gui_State = struct(‘gui_Name’, mfilename, …
‘gui_Singleton’, gui_Singleton, …
‘gui_OpeningFcn’, @faltu_OpeningFcn, …
‘gui_OutputFcn’, @faltu_OutputFcn, …
‘gui_LayoutFcn’, [] , …
‘gui_Callback’, []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code – DO NOT EDIT

% — Executes just before faltu is made visible.
function faltu_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved – to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to faltu (see VARARGIN)

% Choose default command line output for faltu
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes faltu wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% — Outputs from this function are returned to the command line.
function varargout = faltu_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved – to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% — Executes on button press in load.
function load_Callback(hObject, eventdata, handles)
% hObject handle to load (see GCBO)
% eventdata reserved – to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.fileName=uigetfile(‘*.xlsx’)
guidata(hObject,handles)

setPopupmenuString(handles.popupmenuY,eventdata,handles)
setPopupmenuString(handles.popupmenuX,eventdata,handles)

set(handles.popupmenuX,’callback’,’faltu(”updateAxes”,hObject,eventdata,guidata(hObject))’)
set(handles.popupmenuY,’callback’,’faltu(”updateAxes”,hObject,eventdata,guidata(hObject))’)

function setPopupmenuString(hObject, eventdata,handles)
fileName=handles.fileName;
[numbers, colNames]= xlsread(fileName);
set(hObject,’string’,colNames);

function[x y] = readexcelfile(fileName,xcol,ycol)
a=xlsread(fileName);
x=a(:,xcol);
y=a(:,ycol);

function updateAxes(hObject, eventdata,handles)
xcol=get(handles.popupmenuX,’values’);
ycol=get(handles.popupmenuY,’values’);
fileName=handles.fileName;
[x y] = readexcelfile(fileName,xcol,ycol)
plot(handles.axes1,x,y)

% — Executes on selection change in popupmenuy.
function popupmenuX_Callback(hObject, eventdata, handles)
% hObject handle to popupmenuy (see GCBO)
% eventdata reserved – to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,’String’)) returns popupmenuy contents as cell array
% contents{get(hObject,’Value’)} returns selected item from popupmenuy

% — Executes during object creation, after setting all properties.
function popupmenuX_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenuy (see GCBO)
% eventdata reserved – to be defined in a future version of MATLAB
% handles empty – handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,’BackgroundColor’), get(0,’defaultUicontrolBackgroundColor’))
set(hObject,’BackgroundColor’,’white’);
end

% — Executes on selection change in popupmenuY.
function popupmenuY_Callback(hObject, eventdata, handles)
% hObject handle to popupmenuY (see GCBO)
% eventdata reserved – to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,’String’)) returns popupmenuY contents as cell array
% contents{get(hObject,’Value’)} returns selected item from popupmenuY

% — Executes during object creation, after setting all properties.
function popupmenuY_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenuY (see GCBO)
% eventdata reserved – to be defined in a future version of MATLAB
% handles empty – handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,’BackgroundColor’), get(0,’defaultUicontrolBackgroundColor’))
set(hObject,’BackgroundColor’,’white’);
end

These postings are the author's and don't necessarily represent the opinions of MathWorks.