M-File Scripts - 4.2 | 4. Introduction to programming in MATLAB | IT Workshop (Sci Lab/MATLAB)
Students

Academic Programs

AI-powered learning for grades 8-12, aligned with major curricula

Professional

Professional Courses

Industry-relevant training in Business, Technology, and Design

Games

Interactive Games

Fun games to boost memory, math, typing, and English skills

M-File Scripts

4.2 - M-File Scripts

Enroll to start learning

You’ve not yet enrolled in this course. Please enroll for free to listen to audio lessons, classroom podcasts and take practice test.

Practice

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Introduction to M-File Scripts

🔒 Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Today, we're going to talk about M-file scripts in MATLAB. These scripts are essentially a way to save a series of commands so you can run them multiple times. Can anyone tell me why this might be useful?

Student 1
Student 1

It would save time because you don’t have to enter the commands repeatedly.

Teacher
Teacher Instructor

Exactly! Saving time is a big benefit. You can also edit and modify your commands easily. Remember, the files end in .m. Does anyone know what you call these files?

Student 2
Student 2

They are called M-files!

Teacher
Teacher Instructor

Right! M-files can be scripts or functions. Now let’s dive into how to create one. It's very straightforward. You can use the MATLAB editor to do this. Has anyone used the MATLAB editor before?

Student 3
Student 3

Yes, I have! It’s a text editor for writing code, right?

Teacher
Teacher Instructor

That's correct! Let’s summarize this session: M-file scripts allow you to save and execute commands, making your workflow more efficient.

Creating and Running a Script

🔒 Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Let’s walk through creating a simple script file. When you want to create a new script, what do you do in MATLAB?

Student 4
Student 4

You go to File, then New, and select M-file!

Teacher
Teacher Instructor

Exactly! Then you write your commands in the file. For example, let's define a matrix A and a vector b, and solve for x. What do you think happens when we save it as example1.m?

Student 1
Student 1

You can run it by typing example1 in the Command Window!

Teacher
Teacher Instructor

Right again! Running the script will execute all the commands in order. And then, we can use `whos` to check which variables are in the workspace after running the script.

Student 3
Student 3

Will that include variables that are already in the workspace?

Teacher
Teacher Instructor

Great question! Yes, this leads us to the concept of side effects, which we'll discuss next. Remember, scripts can overwrite existing variables!

Examples of M-File Scripts

🔒 Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Let's look at some examples of M-file scripts. The first one we discussed solves a system of equations. Can someone describe the steps taken in that example?

Student 2
Student 2

We defined the matrix A and vector b, then used the backslash operator to solve for x.

Teacher
Teacher Instructor

Exactly! Now, what about the second example with the cosine functions? Who can explain what we did there?

Student 4
Student 4

We created a range of x values, defined three cosine functions, and then plotted them!

Teacher
Teacher Instructor

Fantastic! Plotting is a crucial aspect of MATLAB. The visualization helps in understanding the results. Let’s recap: we explored solving equations and plotting functions using scripts.

Understanding Script Side Effects

🔒 Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Now, let's discuss the side effects of scripts. What do you all think happens when we run a script and overwrite some existing variables?

Student 1
Student 1

It could change the results unexpectedly since the script might use those variables.

Teacher
Teacher Instructor

Exactly! That’s a significant concern. This is why for complex tasks, we often prefer using function M-files that have a separate workspace.

Student 3
Student 3

Can you explain the difference between scripts and functions again?

Teacher
Teacher Instructor

Sure! Scripts do not accept input or return output, while functions can. Functions have their own workspace, avoiding the side effects we've discussed. To remember this, think 'Scripts Save, Functions Function!'.

Student 2
Student 2

That's a catchy way to remember it!

Introduction & Overview

Read summaries of the section's main ideas at different levels of detail.

Quick Overview

M-file scripts in MATLAB are external files containing a sequence of commands that can be executed, making it easier to reuse and modify code.

Standard

In this section, we explore M-file scripts, which allow users to save and execute sequences of MATLAB commands in .m files. We also discuss the creation and execution process, potential side effects of script execution, and differences between scripts and functions.

Detailed

M-File Scripts

M-file scripts, commonly referred to as scripts, are external files with a .m extension that contain a sequence of MATLAB statements. These scripts facilitate the automation of tasks in MATLAB by allowing users to save a series of commands and execute them multiple times without needing to re-enter the commands manually in the Command Window.

Key Points About M-File Scripts

  • Creation: M-files can be created directly using the MATLAB editor. A file can be saved by entering the desired commands and saving it with an appropriate name (e.g., example1.m).
  • Execution: Scripts can be run in the Command Window by typing the filename without the .m extension (e.g., example1). The commands in the script will execute sequentially.
  • Workspace Impact: All variables defined in the script become part of the workspace, which may lead to unintended consequences if variables with the same name already exist.
  • Examples: Two illustrative examples are provided:
  • Solving a system of equations using matrix operations in MATLAB.
  • Plotting multiple cosine functions over a specified interval.
  • Side Effects: Scripts can overwrite existing variables in the workspace and may be influenced by their state. Due to these potential issues, for complex applications, function M-files are recommended instead.

Youtube Videos

Introduction to Scilab for BEGINNERS | Arrays | Conditional Statements, Loops | Functions
Introduction to Scilab for BEGINNERS | Arrays | Conditional Statements, Loops | Functions

Audio Book

Dive deep into the subject with an immersive audiobook experience.

Introduction to M-File Scripts

Chapter 1 of 4

🔒 Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

A script file is an external file that contains a sequence of MATLAB statements. Script files have a filename extension .m and are often called M-files. M-files can be scripts that simply execute a series of MATLAB statements, or they can be functions that can accept arguments and can produce one or more outputs.

Detailed Explanation

M-File scripts are files that contain MATLAB commands and end with the '.m' file extension. These scripts allow users to save a series of commands so they can be run repeatedly without having to type them out each time in the Command Window. They can either just execute commands or function as scripts that can take inputs and produce outputs.

Examples & Analogies

Think of an M-file script like a recipe stored in a cookbook. Instead of writing down the steps to make your favorite dish each time, you can just follow the recipe whenever you want to cook.

Example 1: Solving a System of Equations

Chapter 2 of 4

🔒 Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

Consider the system of equations:
x+2y +3z = 1
3x+3y +4z = 1
2x+3y +3z = 2
Find the solution x to the system of equations.

Solution:
Use the MATLAB editor to create a file: File New M-file.
Enter the following statements in the file:
A = [1 2 3; 3 3 4; 2 3 3];
b = [1; 1; 2];
x = A\b
Save the file, for example, example1.m.
Run the file, in the command line, by typing:

example1
x =
-0.5000
1.5000
-0.5000
When execution completes, the variables (A, b, and x) remain in the workspace. To see a listing of them, enter whos at the command prompt.

Detailed Explanation

In this example, a MATLAB script solves a system of linear equations. The user creates a new M-file and inputs the matrix of coefficients and the constant terms. By running the script, MATLAB computes the values for the variables involved in the equations, and those values are available later in the workspace for further analysis or use.

Examples & Analogies

Imagine you have a complicated math problem that you need to solve over and over again. Instead of solving it on paper every single time, you write down a formula or method in a notebook. Each time you need the answer, you just follow the steps you've written down.

Example 2: Plotting Cosine Functions

Chapter 3 of 4

🔒 Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

Plot the following cosine functions, y = 2cos(x), y = cos(x), and y = 0.5 cos(x), in the interval 0 ≤ x ≤ 2π. Create a file, say example2.m, which contains the following commands:
x = 0:pi/100:2pi;
y1 = 2
cos(x);
y2 = cos(x);
y3 = 0.5cos(x);
plot(x,y1,'--',x,y2,'-',x,y3,':')
xlabel('0 ≤ x ≤ 2π')
ylabel('Cosine functions')
legend('2
cos(x)','cos(x)','0.5cos(x)')
title('Typical example of multiple plots')
axis([0 2
pi -3 3])
Run the file by typing example2 in the Command Window.

Detailed Explanation

This example demonstrates how to create a plot of multiple cosine functions using an M-file script. The script defines the x values over a specified range and calculates the corresponding y values for three different cosine functions. After that, it generates a plot with appropriate labels and legends. Running this script provides a visual representation of the equations, which can help in understanding their behavior.

Examples & Analogies

Consider this like planning a small event. You might write down everything you need to do and the details in a list. When the day comes, instead of trying to remember every single step, you just follow your list step by step to ensure everything goes smoothly.

Script Side-Effects

Chapter 4 of 4

🔒 Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

All variables created in a script file are added to the workspace. This may have undesirable effects, because:
1. Variables already existing in the workspace may be overwritten.
2. The execution of the script can be affected by the state variables in the workspace.
As a result, because scripts have some undesirable side-effects, it is better to code any complicated applications using rather function M-file.

Detailed Explanation

When you run a script, all the variables it creates are added to the MATLAB workspace. If there are already variables with the same names, they can be overwritten, possibly leading to unexpected results. Additionally, if the script relies on certain variables being in the workspace, their current values can affect how the script runs. To avoid these issues, it is often recommended to use functions instead.

Examples & Analogies

Imagine you have a large shared box where everyone in your class stores their supplies. If you add more supplies into the box without checking what others have, you might accidentally take someone else's items or confuse your materials with theirs. Using a separate, personal box for your supplies would help avoid this chaos.

Key Concepts

  • M-file: A file type used for MATLAB scripts or functions.

  • Scripts: A type of M-file that executes sequences of commands.

  • Workspace: Where MATLAB stores variables created during a session.

  • Side effects: Unintended changes to variables when running scripts.

Examples & Applications

Example 1: Solving a system of equations using matrix operations in MATLAB.

Example 2: Plotting multiple cosine functions over an interval.

Memory Aids

Interactive tools to help you remember key concepts

🎵

Rhymes

To save commands, you write them down, in an M-file, your coding crown.

📖

Stories

Imagine you’re a chef writing a recipe. Each command in an M-file is a step in your culinary creation, easy to follow and repeat.

🧠

Memory Tools

Remember: 'Scripts Save, Functions Function!' to distinguish their roles.

🎯

Acronyms

M-File

'MATLAB File' — the key file extension for scripts and functions.

Flash Cards

Glossary

Mfile

A file containing MATLAB code saved with a .m extension.

Script

A sequence of MATLAB commands saved in an M-file that can be executed as a single program.

Workspace

A storage area in MATLAB that holds variables created during a session.

Side effects

Unintended consequences that may result from executing a script, such as overwriting existing variables.

Reference links

Supplementary resources to enhance your learning experience.