File Exchange Pick of the Week

August 13th, 2007

Video series: Reading Excel data into MATLAB with a GUI

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.

133 Responses to “Video series: Reading Excel data into MATLAB with a GUI”

  1. Marcelo replied on :

    Excellent videos. I never made any GUI, so this lesson is going to be a start.

  2. Gerd Kunert replied on :

    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

  3. Doug replied on :

    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

  4. Mike replied on :

    Excellent Videos! This way form to learn MatLab it’s simply awesome. Great job!

  5. Mauricio Argote-Cortes replied on :

    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

  6. Richard Lim replied on :

    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?

  7. Doug replied on :

    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

  8. Richard Lim replied on :

    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

  9. FFA replied on :

    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]

  10. Trevor replied on :

    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

  11. Maryam replied on :

    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?

  12. Doug replied on :

    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

  13. farasha replied on :

    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

  14. farasha replied on :

    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?

  15. Doug replied on :

    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

  16. sivapriya replied on :

    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

  17. Doug replied on :

    Sivapriya,

    I think you want:

    Spreadsheet link EX
    http://www.mathworks.com/products/excellink/

    MATLAB Builder EX
    http://www.mathworks.com/products/matlabxl/index.html

    Doug

  18. Jason replied on :

    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

  19. Doug replied on :

    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

  20. izzri replied on :

    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

  21. Doug replied on :

    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

  22. Hamid replied on :

    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

  23. Doug replied on :

    I have not blogged it yet, but I have the video you seek on the file Exchange:

    http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=19278&objectType=FILE

    Enjoy,
    Doug

  24. Matt replied on :

    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

  25. Doug replied on :

    Matt,

    I think you want this:

    http://blogs.mathworks.com/pick/2008/02/26/matlab-basics-getting-a-directory-listing/

    Doug

  26. Antonio Macanita replied on :

    Excellent. Thanks a lot.

  27. Jon replied on :

    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.

  28. Scott Hirsch replied on :

    Jon –

    You definitely seem to be on the right track. I’ve been working with others here in MATLAB land to study the experience of new-ish MATLAB users, so I’d be happy to offer some help (in exchange for you telling us what’s easy and what’s hard for you). Drop me a line – my email is on my MATLAB Central page. (http://www.mathworks.com/matlabcentral/fileexchange/loadAuthor.do?objectType=author&objectId=919425)

    -scott

  29. Jon replied on :

    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?)

  30. Henry replied on :

    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.

  31. Doug replied on :

    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

  32. maram replied on :

    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

  33. Doug replied on :

    Maram,

    You might want to look at the Database toolbox.

    http://www.mathworks.com/products/database/

    Doug

  34. Hussein replied on :

    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

  35. Doug replied on :

    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

  36. Niaz replied on :

    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

  37. Doug replied on :

    Niaz,

    I made a text file, of similar size, and did not have an issue.

    a = rand(2500);
    save foo.txt a -ascii
    importdata foo.txt

    How is AMTLAB telling you the file is too large? What are you doing to import the file?

    you might want to try this function:
    http://www.mathworks.com/access/helpdesk/help/techdoc/ref/textscan.html

    -Doug

  38. atripathy replied on :

    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,

  39. Doug replied on :

    @atripathy.

    http://blogs.mathworks.com/videos/2007/10/18/matlab-basics-getting-started-from-excel/

    This one should help, all Excel posts are here:

    http://blogs.mathworks.com/videos/category/excel/

    Doug

  40. atripathy replied on :

    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,

  41. Bob replied on :

    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?

  42. theo replied on :

    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

  43. Doug replied on :

    Theo,

    http://www.mathworks.com/access/helpdesk/help/techdoc/ref/xlsread.html

    This shows how you can specify not just the range, but also the sheet you read from. Once you do that, you would make a series of reads from the different sheets and then you could plot that data as normal.

    -Doug

  44. theo replied on :

    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

  45. Doug replied on :

    Theo,

    The SEE ALSO for the XLSREAD that I mentioned above lists

    http://www.mathworks.com/access/helpdesk/help/techdoc/ref/xlsfinfo.html

    That will give you the names of the other sheets in the file.

    Doug

  46. Sean Lee replied on :

    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.

  47. Sean Lee replied on :

    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.

  48. Doug replied on :

    Sean,

    This is a multi-part problem:

    Import into MATLAB
    FFT of data
    Plot data

    Which part are you stuck on, and what have you tried that does not work?

    It sounds like this example in MATLAB:

    http://www.mathworks.com/products/matlab/demos.html?file=/products/demos/shipping/matlab/sunspots.html

    Doug

  49. theo replied on :

    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?

  50. Bob replied on :

    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

  51. theo replied on :

    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?

  52. theo replied on :

    TY alot it works!!!!!i am just rookie=)

  53. Sean Lee replied on :

    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.

  54. theo replied on :

    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?

  55. Doug replied on :

    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

  56. Doug replied on :

    Theo,

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

    Doug

  57. theo replied on :

    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

  58. Steve L replied on :

    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.

  59. ashish replied on :

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

    Thanks
    Ashish Singh

  60. Doug replied on :

    Ashish,

    I think you are looking for QUAD:

    http://www.mathworks.com/access/helpdesk/help/techdoc/ref/quad.html

    Doug

  61. Steve L replied on :

    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.

  62. Robert Edwards replied on :

    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

  63. Doug replied on :

    @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

  64. Doug replied on :

    @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

  65. Tony Silva replied on :

    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 !!

  66. Doug replied on :

    @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

  67. Tony Silva replied on :

    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

  68. Doug replied on :

    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

  69. Atschau replied on :

    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.

  70. Kirsten Miles replied on :

    How can I do this if I have a third column, a z variable that I want to show in a scatter?

  71. Doug replied on :

    @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

  72. Luke replied on :

    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

  73. neo replied on :

    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.

  74. Doug replied on :

    @Neo,

    Please see

    http://www.mathworks.com/support

    Doug

  75. Jade replied on :

    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

  76. Steve L replied on :

    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}
    
  77. Elly replied on :

    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.

  78. Doug replied on :

    @Elly,

    Please contact http://www.mathworks.com/support send the relevant code and we will figure this out.

  79. Bashir replied on :

    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>

  80. Doug replied on :

    @bashir,

    Please send the code to

    http://www.mathworks.com/support

    We can help you better there.

    Doug

  81. Efan replied on :

    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??

  82. Doug replied on :

    @efan,

    Try the Excel file. If it does not work, save it as a csv file. That will work.

    For the compiling, please send more details to:

    http://www.mathworks.com/support

  83. yTheta replied on :

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

  84. Syaza replied on :

    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

  85. Doug replied on :

    @Syaza,

    I think you will be interested in cell2mat and datenum.

    Doug

  86. Syaza replied on :

    Doug,

    It worked, thanks a lot!

    Syaza

  87. Chris R. replied on :

    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.

  88. Christopher R replied on :

    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.

  89. Doug replied on :

    @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

  90. Christopher R replied on :

    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

  91. Christopher R replied on :

    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!

  92. Doug replied on :

    @Christopher,

    Sometimes expediency wins!

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

    Doug

  93. saurabh replied on :

    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

  94. Doug replied on :

    @Saurabh

    I need more context here to help you.

    Doug

  95. saurabh replied on :

    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

  96. sgayawal replied on :

    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.

  97. Doug replied on :

    @sgalawal

    What have you tried?

    dlmread should work pretty well.

    Doug

  98. Ricardo replied on :

    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.

  99. Ricardo replied on :

    ah, sorry :), I’m using MatLab R2010a version 7.10.0.

  100. Doug replied on :

    @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

  101. Ricardo replied on :

    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.

  102. Doug replied on :

    @Ricardo,

    Please contact http://www.mathworks.com/support We can help you best there.

    Doug

  103. sgayawal replied on :

    @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.

  104. Doug replied on :

    @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

  105. Gurinder replied on :

    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))

  106. Harm replied on :

    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

  107. Doug replied on :

    @everyone,

    I need more context to answer these questions. Please see

    http://www.mathworks.com/support they can help you the best.

    Doug

  108. Aaron replied on :

    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

  109. Doug replied on :

    @Aaron,

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

    Doug

  110. KT replied on :

    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?

  111. Doug replied on :

    @KT

    Sorry, they have been removed.

    Doug

  112. Amy replied on :

    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

  113. Doug replied on :

    @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

  114. Amy replied on :

    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?

  115. Doug replied on :

    @Amy,

    did you check the signature that GUIDE produces in the newer version? It might have changed.

    If you have checked, send the code to

    http://www.mathworks.com/support

    That will get to me or a colleague and get an answer quickly.

    Doug

  116. Kishore Kumar replied on :

    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

  117. Doug replied on :

    @Kishore,

    Try xlswrite.

    Doug

  118. Reza replied on :

    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

  119. Doug replied on :

    @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

  120. Amine_lamo replied on :

    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

  121. Ean replied on :

    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

  122. Femi replied on :

    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

  123. chandru replied on :

    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…

  124. Diego replied on :

    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?

  125. Arif replied on :

    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

  126. hussnain replied on :

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

  127. hussnain replied on :

    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

  128. Bhuiyan replied on :

    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

  129. Ralph replied on :

    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.

  130. alizade replied on :

    thanks, this video is very usefull

  131. Mady replied on :

    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

  132. Jessel replied on :

    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’
    ” ”
    ” ”
    ” ”
    ” ”
    ” ”
    ” ”
    ” ”
    ” ”
    ” ”
    ” ”
    ” ”

  133. Jessel replied on :

    all I just want to skip the first column and only the fruit name are available on the popup menu…

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


MathWorks

Brett & Jiro share their favorite user-contributed submissions from the File Exchange.

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