
How to create a GUI in MATLAB ?

Hello friends! Today, we will learn how to create a GUI in MATLAB. GUI stands for graphical user interface: a window containing controls such as buttons, text fields and plots that let someone operate a program without typing every instruction in the Command Window. Our first application will be deliberately small so that we can understand what happens behind each control.
We will enter a message, press Start and display that message elsewhere in the window. Although this sounds simple, it introduces the same important ideas used in larger engineering applications: reading input, responding to an event, validating data and updating an output. Once these steps make sense, adding a calculation or graph becomes much easier.
This article originally used MATLAB's GUIDE editor. We will preserve that illustrated walkthrough for readers maintaining older projects, while also explaining how to build the example with current UI components. Choose the workflow that matches your MATLAB release instead of expecting an old menu or command to appear unchanged.
Choose the Right MATLAB GUI Workflow
MathWorks removed the GUIDE interactive design environment in R2025a. App Designer is the visual design route for new MATLAB apps. Existing GUIDE applications are a separate matter: removing their layout editor does not mean that every existing application immediately stops running. Consult the official GUIDE migration guidance before updating a maintained project.
A useful third option is to create the interface programmatically. Instead of dragging controls onto a canvas, we create a figure and its components in an ordinary MATLAB function. This makes a small teaching example easy to copy, inspect and modify. MathWorks documents this approach under developing apps programmatically.
| Workflow | Typical files | Best use here |
|---|---|---|
| App Designer | An .mlapp file | Creating a new app with a visual layout editor |
| Programmatic UI | An .m function file | Learning exactly how controls and callbacks connect |
| Legacy GUIDE | A .fig file and associated .m code | Understanding the original screenshots and older application |
Do not mix component properties blindly between these systems. An older edit-style uicontrol stores text in String. A modern text edit field exposes Value, while a modern label displays Text. The idea is similar, but using the wrong property produces an error rather than automatically translating the code.
Define What the Application Should Do
Before opening a design tool, describe the interaction. The user types a single-line message in an input field. Pressing Start reads that message. Empty input, including only spaces, produces a useful error message. Valid input replaces the displayed result. The application remains open so the user can try another message.
The original completed interface illustrates this arrangement. The button, editable field and output text each have one clear responsibility.
Notice that a control's label and its programmatic name are different things. A button can display Start while the variable referring to it is named startButton. Meaningful names help us read the program, whereas the visible label helps the person operating it.
We will also make one explicit choice about whitespace: leading and trailing spaces are removed, while spaces inside the message remain. A different application might preserve every character, but that decision should be intentional. Here, trimming prevents a message containing only spaces from appearing to be a successful result.
Create the Interface in App Designer
- Open App Designer from MATLAB's Apps tools or enter
appdesignerin the Command Window. - Create a blank app and save it under a meaningful name.
- Add a text edit field, a push button and a label to the design area.
- Set the button text to Start and label the input so its purpose is obvious.
- Give the components meaningful names, such as MessageEditField and OutputLabel.
- Create a ButtonPushedFcn callback for the Start button.
In the callback, read app.MessageEditField.Value, trim it, and check whether it is empty. For valid text, assign the result to app.OutputLabel.Text. For empty text, show an alert using the app's figure as its parent. Component names in your code must match those in your own app.
App Designer maintains the generated class structure and layout code. Put your interaction logic inside the appropriate callback or your own helper method; do not replace the entire generated app with a fragment copied from an unrelated example. Save the app before running it so that its file location is clear.
For a resizable interface, use a grid layout and give the input and output enough space. A label that looks correct at one window size may clip a longer message. Test the longest message you intend to support and decide whether a text area would be more appropriate than a single-line label.
A Complete Programmatic Text-Transfer Example
The following independent example implements the same interaction without requiring a saved visual layout. Save it as simpleTextGui.m in the current folder or on the MATLAB path, then call simpleTextGui. The function name and file name should match.
function simpleTextGui
fig = uifigure('Name','Text transfer example', ...
'Position',[100 100 520 240]);
grid = uigridlayout(fig,[4 1]);
grid.RowHeight = {24,34,34,'1x'};
grid.Padding = [16 16 16 16];
uilabel(grid,'Text','Enter a message:');
inputField = uieditfield(grid,'text');
uibutton(grid,'push','Text','Start', ...
'ButtonPushedFcn',@copyMessage);
outputLabel = uilabel(grid,'Text','Your message appears here.', ...
'Interpreter','none','WordWrap','on');
function copyMessage(~,~)
message = strtrim(inputField.Value);
if isempty(message)
uialert(fig,'Enter some text before pressing Start.', ...
'Message required');
return
end
outputLabel.Text = message;
end
end
The nested function can access the component variables created by the outer function. Its two ignored inputs are the callback source and event information supplied by MATLAB. We do not need them for this operation, but their positions still belong in the function signature. See the official programmatic callback documentation for other ways to pass information.
The result label uses a plain-text interpreter so that underscores or other formatting characters in a message are displayed as text. Word wrapping helps longer messages fit the available space. These are presentation choices; they do not change the underlying input value or execute anything the user enters.
This example is supplied as source to run in your own compatible MATLAB installation. The original screenshots below do not show this newer function, and no fresh execution of it is claimed here. If your older release does not support a shown property, use its installed documentation to adapt the layout.
Understanding the Original GUIDE Walkthrough
The remaining illustrated steps describe the historical editor. On a MATLAB release that includes GUIDE, entering guide opens its design tools. On a newer release where the editor has been removed, use the earlier App Designer section instead of treating an unavailable command as an installation fault.
The original startup dialog offers a new GUI or an existing GUI. Selecting a blank layout creates an empty interface. Opening an existing layout instead loads its saved controls, and should be done only with project files you trust.
The layout canvas then provides controls on its left side. A pushbutton creates an action, an edit field accepts input, and a static text control displays information. These are enough for our first project; there is no benefit in adding every available control before defining its purpose.
Add the Start Button
Drag a pushbutton onto the canvas and adjust its size. Leave space above or below it for the input and output. Keeping a sensible reading order helps users understand what to enter and when to press the button.
Double-click the button to inspect its properties. In GUIDE, the String property controls the visible caption, so change it to Start. The Tag property identifies the control in the generated handles structure. Changing a caption does not automatically rename every reference to that control in your code.
Save the layout and its associated code. GUIDE generates functions for initialization and callbacks. This code is not uploaded into the button as if the button were a microcontroller; MATLAB invokes the relevant function when an event occurs.
Add Output and Input Controls
Add a static text control to display the result. Its properties include the displayed String, alignment and font settings. Use a descriptive initial message such as Your message appears here, so that an empty output is not confused with a broken interface.
The original tutorial places the The Engineering Projects website address in this control and changes its appearance. That is a useful way to explore formatting, but readability should determine the final font size and contrast.
Add an edit text control and set its Tag to edit1 if you want to use the legacy callback below unchanged. Set the output text control's Tag to text2. Keep the input in single-line mode for this example; a multiline control can return data in a form that needs different handling.
Attach the Callback to the Correct Button
Open the Start button's callback through the editor's callback menu. This establishes where the interaction code belongs. Editing the input field's creation function instead would not make the code run each time Start is pressed.
The generated callback receives hObject, eventdata and handles. The handles structure contains references to controls identified by their tags. Our code reads one control and changes another; the visible interface is updated through those references.
function pushbutton1_Callback(hObject,eventdata,handles)
message = strtrim(get(handles.edit1,'String'));
if isempty(message)
errordlg('Enter some text before pressing Start.', ...
'Message required');
return
end
set(handles.text2,'String',message);
end
Use the callback name that GUIDE generated for your actual button. Do not create a second unrelated function and expect the original button to discover it automatically. Also retain the surrounding generated file structure; the small function above is the interaction logic, not a complete replacement for the project.
The original version printed an error in the Command Window. A dialog is easier for someone using only the app to notice. If you do log an error with fprintf, a newline is written as \n, not as a letter n appended to the sentence.
Run the Text-Transfer Interaction
Run the saved GUI and type a message in the edit field. Typing changes the input control, but it does not yet perform the Start-button action in this design.
Now click Start. The callback reads the current input and places the validated message in the static text control. Pressing Enter inside an edit field is not automatically equivalent to clicking Start unless you have explicitly implemented that interaction.
The original downloadable project and demonstration video remain here for readers following the older GUIDE workflow. They are historical teaching assets, not an App Designer conversion of the revised examples.
Download Simple GUI Project in MATLABKeep Data and Calculations Separate from the Interface
A GUI becomes difficult to maintain when every algorithm, file operation and formatting decision is packed into one button callback. Keep the callback responsible for reading input, calling a calculation function and displaying the result. Write the calculation so it can also be called directly from the Command Window with known inputs.
For example, an Ohm's-law tool could accept voltage and resistance, then compute I = V/R. With 12 V and 240 ohms, the result is 0.05 A, or 50 mA. Validate that the resistance is positive and finite before dividing. Displaying units avoids a misleading result such as simply 0.05.
Text that resembles a number is still text until it is converted. For an older text field, str2double provides a direct conversion without evaluating the input as MATLAB code. An unsuccessful conversion returns NaN, as described in the MathWorks conversion reference. Check validity and the permitted physical range before using the result.
A modern numeric edit field can simplify number entry, but application constraints remain your responsibility. A mathematically valid negative number may be invalid as a resistance. Likewise, infinity is not an acceptable supply voltage just because a numeric representation exists.
Where Should Shared Values Be Stored?
For a small programmatic app, nested callbacks can share variables from the main function. In an App Designer app, properties can hold state needed by several callbacks. Avoid scattering data through unrelated base-workspace variables whose names might be overwritten by another script.
When maintaining GUIDE code that stores extra values in handles, remember to write the updated structure back with guidata. Changing a graphics object's property and changing an ordinary field of a structure are different operations. The official guidata reference explains the legacy mechanism and recommends figure UserData for many programmatic cases.
Review the App Before Adding More Features
| Action | Expected result |
|---|---|
| Click Start with no text | A clear message requests input |
| Enter only spaces | Input is rejected after trimming |
| Enter an ordinary sentence | The sentence appears in the output |
| Change the message and click again | The latest value replaces the previous result |
| Enter punctuation and underscores | Content is displayed as intended, without unwanted formatting |
| Resize the window | Controls remain usable and text does not hide the button |
If a button appears to do nothing, check that its callback is assigned, then place a breakpoint at the first executable line. Inspect the input value before changing the code. A misspelled component name, wrong property or callback attached to the wrong control is more likely than a mysterious failure of MATLAB itself.
Long calculations require additional care. A lengthy blocking callback can make the interface appear frozen. Start with short operations, provide a status indication and prevent accidental duplicate starts. For substantial work, design cancellation and asynchronous execution using the facilities appropriate to your MATLAB release and licensed products.
Saving an app file does not automatically create a standalone executable for computers without MATLAB. Deployment is a separate workflow with its own product and runtime requirements. First make the app reliable in the development environment before deciding how other people will run it.
Also test keyboard navigation. Someone should be able to reach the input and Start button without guessing where focus has moved. Keep labels visible, avoid using color as the only indication of an error, and explain how to correct invalid input. If a future version adds a Reset button, define whether it clears only the displayed result or also erases the input. Consistent behavior matters more than adding decorative controls that make a small app harder to understand.
Useful Next Projects
Once text transfer works, try adding a numerical calculation or plotting a small dataset. Then explore sending data through a serial port in MATLAB, where you must also manage connection state and communication errors.
Our projects on speech recognition using correlation, DTMF decoding and hexapod simulation provide ideas for more substantial interfaces. Keep their processing algorithms separate from the controls.
If distributing older project files, the articles on MATLAB P-code and packaging Simulink work with S-functions discuss historical approaches. Packaging should not be confused with strong protection for credentials or private data.
Frequently Asked Questions
Why does the guide command no longer open an editor?
The GUIDE interactive editor was removed in R2025a. Use App Designer for new visual designs and the documented migration tools for older projects.
Do I need Simulink for this text-transfer example?
No. The example uses MATLAB interface components and callbacks. Simulink is relevant when your application also runs or controls a Simulink model.
Why is my message not copied when I type it?
This app deliberately updates the output when Start is pressed. Updating on every edit requires a different callback and should be implemented explicitly.
Can I reuse the same calculation in several apps?
Yes. Put the calculation in a separate function with clear inputs and outputs, then call it from each interface. That also makes it easier to check the numerical behavior independently.
Should I copy the legacy handles code into App Designer?
No. Translate the component references and properties to the App Designer app structure. The teaching sequence remains the same, but the underlying objects differ.
Very nice tutorial brother.
Can you explain a little bit about the code of function that you wrote in "Callback" Button, since I'm not very experienced in this. Specially about the "handles.xyz". Thanks

























Comments
2