SlideShare ist ein Scribd-Unternehmen logo
1 von 17
Engineering H192 - Computer Programming

MATLAB: Script and Function Files
Lecture 19

Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

MATLAB Script Files
• A MATLAB script file (Called an M-file) is a text
(plain ASCII) file that contains one or more
MATLAB commands and, optionally, comments.
• The file is saved with the extension ".m".
• When the filename (without the extension) is
issued as a command in MATLAB, the file is
opened, read, and the commands are executed as
if input from the keyboard. The result is similar
to running a program in C. The following slide is
the contents of an M-file. Note that there are no
prompts (>>).
Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

MATLAB Script Files
% This is a MATLAB script file.
% It has been saved as “g13.m".
load g13.dat;
%Load data file
voltage = g13( : , 4);
%Extract volts vector
time = .005*[1:length(voltage)]; %Create time vector
plot (time, voltage)
%Plot volts vs time
xlabel ('Time in Seconds')
% Label x axis
ylabel ('Voltage')
% Label y axis
title ('Bike Strain Gage Voltage vs Time')
grid
%Put a grid on graph
Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

MATLAB Script Files
• The preceding file is executed by issuing a
MATLAB command:
>> g13
• This single command causes MATLAB to look in
the current directory, and if a file g13.m is found,
open it and execute all of the commands. The
result, in this case, is a plot of the data from
g13.dat.
• If MATLAB cannot find the file in the current
working directory, an error message will appear.
Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

MATLAB Script Files
• When the file is not in the current working
directory, a cd or chdir command may be issued
to change the directory.
>> cd a: % Make a: the current working directory
>> g13

Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

MATLAB Demo
%MATLAB Example use of ginput
clear, clf, hold off
axis ([0, 10, 0, 10])
hold on
plot ([1, 2, 2, 1, 1],[2, 2, 3, 3, 2])
text (1, 1.6, 'Click inside box to quit')
while 1
[x, y, buttun] = ginput (1)
if buttun == 1, plot (x, y, '+r'), end
if buttun == 2, plot (x, y, 'oy'), end
if buttun == 3, plot (x, y, '*g'), end
if x > 1 & x < 2 & y > 2 & y < 3, break;
end
end
hold off
Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

MATLAB Function Files
• A MATLAB function file (called an M-file) is a text
(plain ASCII) file that contains a MATLAB function
and, optionally, comments.
• The file is saved with the function name and the
usual MATLAB script file extension, ".m".
• A MATLAB function may be called from the
command line or from any other M-file.

Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

MATLAB Function Files
• When the function is called in MATLAB, the file is
accessed, the function is executed, and control is
returned to the MATLAB workspace.
• Since the function is not part of the MATLAB
workspace, its variables and their values are not
known after control is returned.
• Any values to be returned must be specified in
the function syntax.
Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

MATLAB Function Files
• The syntax for a MATLAB function definition is:
function [val1, … , valn] = myfunc (arg1, … , argk)
where val1 through valn are the specified
returned values from the function and arg1
through argk are the values sent to the function.
• Since variables are local in MATLAB (as they are
in C), the function has its own memory locations
for all of the variables and only the values (not
their addresses) are passed between the
MATLAB workspace and the function.
Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

MATLAB Function Files
• It is OK to use the same variable names in the
returned value list as in the argument. The effect
is to assign new values to those variables. As an
example, the following slide shows a function
that swaps two values.

Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

Example of a MATLAB Function File
function [ a , b ] = swap ( a , b )
% The function swap receives two values, swaps them,
% and returns the result. The syntax for the call is
% [a, b] = swap (a, b) where the a and b in the ( ) are the
% values sent to the function and the a and b in the [ ] are
% returned values which are assigned to corresponding
% variables in your program.
temp=a;
a=b;
b=temp;

Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

Example of a MATLAB Function File
• To use the function a MATLAB program could
assign values to two variables (the names do not
have to be a and b) and then call the function to
swap them. For instance the MATLAB commands:
>> x = 5 ; y = 6 ; [ x , y ] = swap ( x , y )
result in:
x=
6
y=
5
Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

MATLAB Function Files
• Referring to the function, the comments immediately
following the function definition statement are the
"help" for the function. The MATLAB command:
>>help swap %displays:
The function swap receives two values, swaps them,
and returns the result. The syntax for the call is
[a, b] = swap (a, b) where the a and b in the ( ) are the
values sent to the function and the a and b in the [ ] are
returned values which are assigned to corresponding
variables in your program.
Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

MATLAB Function Files
• The MATLAB function must be in the current
working directory. If it is not, the directory must
be changed before calling the function.
• If MATLAB cannot find the function or its syntax
does not match the function call, an error
message will appear. Failure to change
directories often results in the error message:
Undefined function or improper matrix assignment.
Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

MATLAB Function Files
• When the function file is not in the current
working directory, a cd or chdir command may be
issued to change the directory.
>> cd a: % Make a: the current working directory

Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

MATLAB Function Files
• Unlike C, a MATLAB variable does not have to be
declared before being used, and its data type can
be changed by assigning a new value to it.
• For example, the function factorial ( ) on the next
slide returns an integer when a positive value is
sent to it as an argument, but returns a character
string if the argument is negative.

Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19
Engineering H192 - Computer Programming

MATLAB Function Files
function [n] = factorial (k)
% The function [n] = factorial(k) calculates and
% returns the value of k factorial. If k is negative,
% an error message is returned.
if (k < 0) n = 'Error, negative argument';
elseif k<2 n=1;
else
n = 1;
for j = [2:k] n = n * j; end
end
Winter Quarter

The Ohio State University
Gateway Engineering Education Coalition

Lect 19

Weitere ähnliche Inhalte

Was ist angesagt?

BCA DATA STRUCTURES ALGORITHMS AND PRELIMINARIES MRS SOWMYA JYOTHI
BCA DATA STRUCTURES ALGORITHMS AND PRELIMINARIES MRS SOWMYA JYOTHIBCA DATA STRUCTURES ALGORITHMS AND PRELIMINARIES MRS SOWMYA JYOTHI
BCA DATA STRUCTURES ALGORITHMS AND PRELIMINARIES MRS SOWMYA JYOTHISowmya Jyothi
 
Matlab HTI summer training course_Lecture2
Matlab HTI summer training course_Lecture2Matlab HTI summer training course_Lecture2
Matlab HTI summer training course_Lecture2Mohamed Awni
 
R Programming Tutorial for Beginners - -TIB Academy
R Programming Tutorial for Beginners - -TIB AcademyR Programming Tutorial for Beginners - -TIB Academy
R Programming Tutorial for Beginners - -TIB Academyrajkamaltibacademy
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESSowmya Jyothi
 
R Programming: Introduction to Vectors
R Programming: Introduction to VectorsR Programming: Introduction to Vectors
R Programming: Introduction to VectorsRsquared Academy
 
Best corporate-r-programming-training-in-mumbai
Best corporate-r-programming-training-in-mumbaiBest corporate-r-programming-training-in-mumbai
Best corporate-r-programming-training-in-mumbaiUnmesh Baile
 
Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...
Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...
Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...Flink Forward
 
Apache Flink Deep-Dive @ Hadoop Summit 2015 in San Jose, CA
Apache Flink Deep-Dive @ Hadoop Summit 2015 in San Jose, CAApache Flink Deep-Dive @ Hadoop Summit 2015 in San Jose, CA
Apache Flink Deep-Dive @ Hadoop Summit 2015 in San Jose, CARobert Metzger
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for publiciqbalphy1
 
Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2datamantra
 
Scilab: Computing Tool For Engineers
Scilab: Computing Tool For EngineersScilab: Computing Tool For Engineers
Scilab: Computing Tool For EngineersNaren P.R.
 
Recent Developments in Spark MLlib and Beyond
Recent Developments in Spark MLlib and BeyondRecent Developments in Spark MLlib and Beyond
Recent Developments in Spark MLlib and BeyondXiangrui Meng
 
Introduction to R programming
Introduction to R programmingIntroduction to R programming
Introduction to R programmingAlberto Labarga
 
Overview of Apache SystemML by Berthold Reinwald and Nakul Jindal
Overview of Apache SystemML by Berthold Reinwald and Nakul JindalOverview of Apache SystemML by Berthold Reinwald and Nakul Jindal
Overview of Apache SystemML by Berthold Reinwald and Nakul JindalArvind Surve
 

Was ist angesagt? (19)

BCA DATA STRUCTURES ALGORITHMS AND PRELIMINARIES MRS SOWMYA JYOTHI
BCA DATA STRUCTURES ALGORITHMS AND PRELIMINARIES MRS SOWMYA JYOTHIBCA DATA STRUCTURES ALGORITHMS AND PRELIMINARIES MRS SOWMYA JYOTHI
BCA DATA STRUCTURES ALGORITHMS AND PRELIMINARIES MRS SOWMYA JYOTHI
 
Mbd dd
Mbd ddMbd dd
Mbd dd
 
Matlab HTI summer training course_Lecture2
Matlab HTI summer training course_Lecture2Matlab HTI summer training course_Lecture2
Matlab HTI summer training course_Lecture2
 
R Programming Tutorial for Beginners - -TIB Academy
R Programming Tutorial for Beginners - -TIB AcademyR Programming Tutorial for Beginners - -TIB Academy
R Programming Tutorial for Beginners - -TIB Academy
 
Linked list
Linked listLinked list
Linked list
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
 
R Programming: Introduction to Vectors
R Programming: Introduction to VectorsR Programming: Introduction to Vectors
R Programming: Introduction to Vectors
 
Best corporate-r-programming-training-in-mumbai
Best corporate-r-programming-training-in-mumbaiBest corporate-r-programming-training-in-mumbai
Best corporate-r-programming-training-in-mumbai
 
Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...
Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...
Flink Forward San Francisco 2019: Build a Table-centric Apache Flink Ecosyste...
 
R programming by ganesh kavhar
R programming by ganesh kavharR programming by ganesh kavhar
R programming by ganesh kavhar
 
Apache Flink Deep-Dive @ Hadoop Summit 2015 in San Jose, CA
Apache Flink Deep-Dive @ Hadoop Summit 2015 in San Jose, CAApache Flink Deep-Dive @ Hadoop Summit 2015 in San Jose, CA
Apache Flink Deep-Dive @ Hadoop Summit 2015 in San Jose, CA
 
stacks and queues for public
stacks and queues for publicstacks and queues for public
stacks and queues for public
 
06 uml-component
06 uml-component06 uml-component
06 uml-component
 
Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2Anatomy of Spark SQL Catalyst - Part 2
Anatomy of Spark SQL Catalyst - Part 2
 
Scilab: Computing Tool For Engineers
Scilab: Computing Tool For EngineersScilab: Computing Tool For Engineers
Scilab: Computing Tool For Engineers
 
Recent Developments in Spark MLlib and Beyond
Recent Developments in Spark MLlib and BeyondRecent Developments in Spark MLlib and Beyond
Recent Developments in Spark MLlib and Beyond
 
Introduction to R programming
Introduction to R programmingIntroduction to R programming
Introduction to R programming
 
Overview of Apache SystemML by Berthold Reinwald and Nakul Jindal
Overview of Apache SystemML by Berthold Reinwald and Nakul JindalOverview of Apache SystemML by Berthold Reinwald and Nakul Jindal
Overview of Apache SystemML by Berthold Reinwald and Nakul Jindal
 
Introduction to FreeMat
Introduction to FreeMatIntroduction to FreeMat
Introduction to FreeMat
 

Andere mochten auch

Lecture 02 visualization and programming
Lecture 02   visualization and programmingLecture 02   visualization and programming
Lecture 02 visualization and programmingSmee Kaem Chann
 
Matlab for diploma students(1)
Matlab for diploma students(1)Matlab for diploma students(1)
Matlab for diploma students(1)Retheesh Raj
 
Basics of programming in matlab
Basics of programming in matlabBasics of programming in matlab
Basics of programming in matlabAKANKSHA GUPTA
 
Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105NUST Stuff
 
Program Logic Formulation - Ohio State University
Program Logic Formulation - Ohio State UniversityProgram Logic Formulation - Ohio State University
Program Logic Formulation - Ohio State UniversityReggie Niccolo Santos
 
Matlab programming project
Matlab programming projectMatlab programming project
Matlab programming projectAssignmentpedia
 
Computer programming
Computer programmingComputer programming
Computer programmingSujay Raj
 
Lab 5 array
Lab 5 arrayLab 5 array
Lab 5 arraymkazree
 
aem : Fourier series of Even and Odd Function
aem :  Fourier series of Even and Odd Functionaem :  Fourier series of Even and Odd Function
aem : Fourier series of Even and Odd FunctionSukhvinder Singh
 
Use of computer programming in animal diet formulation
Use of computer programming in animal diet formulationUse of computer programming in animal diet formulation
Use of computer programming in animal diet formulationMilling and Grain magazine
 
MATLAB Based Vehicle Number Plate Identification System using OCR
MATLAB Based Vehicle Number Plate Identification System using OCRMATLAB Based Vehicle Number Plate Identification System using OCR
MATLAB Based Vehicle Number Plate Identification System using OCRGhanshyam Dusane
 

Andere mochten auch (20)

Working with Scientific Data in MATLAB
Working with Scientific Data in MATLABWorking with Scientific Data in MATLAB
Working with Scientific Data in MATLAB
 
Lecture 02 visualization and programming
Lecture 02   visualization and programmingLecture 02   visualization and programming
Lecture 02 visualization and programming
 
Coursee
CourseeCoursee
Coursee
 
Matlab for diploma students(1)
Matlab for diploma students(1)Matlab for diploma students(1)
Matlab for diploma students(1)
 
Mit6 094 iap10_lec01
Mit6 094 iap10_lec01Mit6 094 iap10_lec01
Mit6 094 iap10_lec01
 
Basics of programming in matlab
Basics of programming in matlabBasics of programming in matlab
Basics of programming in matlab
 
Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105
 
Program Logic Formulation - Ohio State University
Program Logic Formulation - Ohio State UniversityProgram Logic Formulation - Ohio State University
Program Logic Formulation - Ohio State University
 
Matlab programming project
Matlab programming projectMatlab programming project
Matlab programming project
 
C++ for beginners
C++ for beginnersC++ for beginners
C++ for beginners
 
Computer programming
Computer programmingComputer programming
Computer programming
 
Apt programming
Apt programmingApt programming
Apt programming
 
Lab 5 array
Lab 5 arrayLab 5 array
Lab 5 array
 
aem : Fourier series of Even and Odd Function
aem :  Fourier series of Even and Odd Functionaem :  Fourier series of Even and Odd Function
aem : Fourier series of Even and Odd Function
 
Use of computer programming in animal diet formulation
Use of computer programming in animal diet formulationUse of computer programming in animal diet formulation
Use of computer programming in animal diet formulation
 
DISE - Programming Concepts
DISE - Programming ConceptsDISE - Programming Concepts
DISE - Programming Concepts
 
MATLAB Based Vehicle Number Plate Identification System using OCR
MATLAB Based Vehicle Number Plate Identification System using OCRMATLAB Based Vehicle Number Plate Identification System using OCR
MATLAB Based Vehicle Number Plate Identification System using OCR
 
NC Programming
NC ProgrammingNC Programming
NC Programming
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
10 Myths for Computer Science
10 Myths for Computer Science10 Myths for Computer Science
10 Myths for Computer Science
 

Ähnlich wie Lecture 19 matlab_script&function_files06

Ähnlich wie Lecture 19 matlab_script&function_files06 (20)

MatlabIntro (1).ppt
MatlabIntro (1).pptMatlabIntro (1).ppt
MatlabIntro (1).ppt
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
EE6711 Power System Simulation Lab manual
EE6711 Power System Simulation Lab manualEE6711 Power System Simulation Lab manual
EE6711 Power System Simulation Lab manual
 
Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4
 
Matlab anilkumar
Matlab  anilkumarMatlab  anilkumar
Matlab anilkumar
 
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptxMATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Matlab Introduction
Matlab IntroductionMatlab Introduction
Matlab Introduction
 
Tutorial2
Tutorial2Tutorial2
Tutorial2
 
Brief Introduction to Matlab
Brief  Introduction to MatlabBrief  Introduction to Matlab
Brief Introduction to Matlab
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docxMATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
MATLAB sessions Laboratory 1MAT 275 Laboratory 1Introdu.docx
 
Kevin merchantss
Kevin merchantssKevin merchantss
Kevin merchantss
 
KEVIN MERCHANT DOCUMENT
KEVIN MERCHANT DOCUMENTKEVIN MERCHANT DOCUMENT
KEVIN MERCHANT DOCUMENT
 
From zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyondFrom zero to MATLAB hero: Mastering the basics and beyond
From zero to MATLAB hero: Mastering the basics and beyond
 
Matlab Manual
Matlab ManualMatlab Manual
Matlab Manual
 
Introduction to Matlab.ppt
Introduction to Matlab.pptIntroduction to Matlab.ppt
Introduction to Matlab.ppt
 
Dsp file
Dsp fileDsp file
Dsp file
 
CPP homework help
CPP homework helpCPP homework help
CPP homework help
 

Kürzlich hochgeladen

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 

Kürzlich hochgeladen (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

Lecture 19 matlab_script&function_files06

  • 1. Engineering H192 - Computer Programming MATLAB: Script and Function Files Lecture 19 Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 2. Engineering H192 - Computer Programming MATLAB Script Files • A MATLAB script file (Called an M-file) is a text (plain ASCII) file that contains one or more MATLAB commands and, optionally, comments. • The file is saved with the extension ".m". • When the filename (without the extension) is issued as a command in MATLAB, the file is opened, read, and the commands are executed as if input from the keyboard. The result is similar to running a program in C. The following slide is the contents of an M-file. Note that there are no prompts (>>). Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 3. Engineering H192 - Computer Programming MATLAB Script Files % This is a MATLAB script file. % It has been saved as “g13.m". load g13.dat; %Load data file voltage = g13( : , 4); %Extract volts vector time = .005*[1:length(voltage)]; %Create time vector plot (time, voltage) %Plot volts vs time xlabel ('Time in Seconds') % Label x axis ylabel ('Voltage') % Label y axis title ('Bike Strain Gage Voltage vs Time') grid %Put a grid on graph Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 4. Engineering H192 - Computer Programming MATLAB Script Files • The preceding file is executed by issuing a MATLAB command: >> g13 • This single command causes MATLAB to look in the current directory, and if a file g13.m is found, open it and execute all of the commands. The result, in this case, is a plot of the data from g13.dat. • If MATLAB cannot find the file in the current working directory, an error message will appear. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 5. Engineering H192 - Computer Programming MATLAB Script Files • When the file is not in the current working directory, a cd or chdir command may be issued to change the directory. >> cd a: % Make a: the current working directory >> g13 Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 6. Engineering H192 - Computer Programming MATLAB Demo %MATLAB Example use of ginput clear, clf, hold off axis ([0, 10, 0, 10]) hold on plot ([1, 2, 2, 1, 1],[2, 2, 3, 3, 2]) text (1, 1.6, 'Click inside box to quit') while 1 [x, y, buttun] = ginput (1) if buttun == 1, plot (x, y, '+r'), end if buttun == 2, plot (x, y, 'oy'), end if buttun == 3, plot (x, y, '*g'), end if x > 1 & x < 2 & y > 2 & y < 3, break; end end hold off Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 7. Engineering H192 - Computer Programming MATLAB Function Files • A MATLAB function file (called an M-file) is a text (plain ASCII) file that contains a MATLAB function and, optionally, comments. • The file is saved with the function name and the usual MATLAB script file extension, ".m". • A MATLAB function may be called from the command line or from any other M-file. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 8. Engineering H192 - Computer Programming MATLAB Function Files • When the function is called in MATLAB, the file is accessed, the function is executed, and control is returned to the MATLAB workspace. • Since the function is not part of the MATLAB workspace, its variables and their values are not known after control is returned. • Any values to be returned must be specified in the function syntax. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 9. Engineering H192 - Computer Programming MATLAB Function Files • The syntax for a MATLAB function definition is: function [val1, … , valn] = myfunc (arg1, … , argk) where val1 through valn are the specified returned values from the function and arg1 through argk are the values sent to the function. • Since variables are local in MATLAB (as they are in C), the function has its own memory locations for all of the variables and only the values (not their addresses) are passed between the MATLAB workspace and the function. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 10. Engineering H192 - Computer Programming MATLAB Function Files • It is OK to use the same variable names in the returned value list as in the argument. The effect is to assign new values to those variables. As an example, the following slide shows a function that swaps two values. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 11. Engineering H192 - Computer Programming Example of a MATLAB Function File function [ a , b ] = swap ( a , b ) % The function swap receives two values, swaps them, % and returns the result. The syntax for the call is % [a, b] = swap (a, b) where the a and b in the ( ) are the % values sent to the function and the a and b in the [ ] are % returned values which are assigned to corresponding % variables in your program. temp=a; a=b; b=temp; Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 12. Engineering H192 - Computer Programming Example of a MATLAB Function File • To use the function a MATLAB program could assign values to two variables (the names do not have to be a and b) and then call the function to swap them. For instance the MATLAB commands: >> x = 5 ; y = 6 ; [ x , y ] = swap ( x , y ) result in: x= 6 y= 5 Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 13. Engineering H192 - Computer Programming MATLAB Function Files • Referring to the function, the comments immediately following the function definition statement are the "help" for the function. The MATLAB command: >>help swap %displays: The function swap receives two values, swaps them, and returns the result. The syntax for the call is [a, b] = swap (a, b) where the a and b in the ( ) are the values sent to the function and the a and b in the [ ] are returned values which are assigned to corresponding variables in your program. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 14. Engineering H192 - Computer Programming MATLAB Function Files • The MATLAB function must be in the current working directory. If it is not, the directory must be changed before calling the function. • If MATLAB cannot find the function or its syntax does not match the function call, an error message will appear. Failure to change directories often results in the error message: Undefined function or improper matrix assignment. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 15. Engineering H192 - Computer Programming MATLAB Function Files • When the function file is not in the current working directory, a cd or chdir command may be issued to change the directory. >> cd a: % Make a: the current working directory Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 16. Engineering H192 - Computer Programming MATLAB Function Files • Unlike C, a MATLAB variable does not have to be declared before being used, and its data type can be changed by assigning a new value to it. • For example, the function factorial ( ) on the next slide returns an integer when a positive value is sent to it as an argument, but returns a character string if the argument is negative. Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19
  • 17. Engineering H192 - Computer Programming MATLAB Function Files function [n] = factorial (k) % The function [n] = factorial(k) calculates and % returns the value of k factorial. If k is negative, % an error message is returned. if (k < 0) n = 'Error, negative argument'; elseif k<2 n=1; else n = 1; for j = [2:k] n = n * j; end end Winter Quarter The Ohio State University Gateway Engineering Education Coalition Lect 19

Hinweis der Redaktion

  1. Instructor notes: This set of slides covers script files and function files. These are Matlab’s programming options.
  2. Instructor notes: There are two types of M-files…script files and function files. We start out with script files. Script files are called M-files because the extension on the file is “.m”. Script files are a collection of Matlab commands that when executed are the same as if the commands had been entered from the keyboard. Variables that are used in script files are equivalent to global variables. A variable that originates in a script file is immediately known in the command window. Variables that originated in the command window are known in the script file. This is one are in which script and function files differ. Function files, like C/C++ functions use local variables which must be passed in and out of the function.
  3. Instructor notes: This example demonstrates several key things about Matlab script files. We’ve got the script file d13.m. In order to invoke it, Matlab’s current working directory must be the same directory as where d13.m is stored, or the entire pathname to the script file must be entered at the command prompt. The load d13.dat command will open the file, d13.dat. Because the entire pathname to d13.dat is not specified, the current working directory must contain d13.dat. The load will open the file and read the entire file into Matlab creating an array called d13 without the “.dat” extension. Note the semicolon at the end of the line. This will prevent the contents of the array from being echoed to the command window. The second line creates a vector called voltage by reading in all of the rows in column 4 from the d13 matrix. Again, note the semicolon at the end of the line. The third line creates a time vector by multiplying 0.005 times a vector that has elements 1 to the length of the voltage vector. The fourth line plots the time on the x-axis and the voltage on the y-axis opening a new window that contains the plot. Lines 5 and 6 add labels to the x-axis and y-axis respectively. Line seven places a title on the plot and line eight puts a grid on the plot.
  4. Instructor notes: As the slide indicates, the d13.m script file is executed by entering d13 at the command prompt when the current working directory is set to the same directory in which d13.m exists. If Matlab cannot find the file, it will display an error message. Note, that you can add to Matlab’s default search path so that files do not have to be located in the current directory.
  5. Instructor notes: If the script file that you want to execute is not in the current directory, then use the cd or chdir commands to move to the correct directory and then execute the script file. Note that there are icons at the top of the command window that allow you to use the mouse to navigate to the desired directory. This may be especially useful when you have some idea of the name or roughly where the file is located rather than knowing the exact name or path. In this example the file is stored on the a: drive at the root level.
  6. Instructor notes: Here we have another script file example…again this one has a lot packed into it. This script file collects mouse clicks and depending on which button was clicked, places a corresponding symbol on the plot window where the mouse was located at the time of the click. Line 1 issues three commands: clear removes all variables from memory, clf clears the figure window, and hold off turns off the plot holding. When the hold is on and multiple plot commands are issued, the plots will be placed on the same figure. In this script the hold is just being initialized to off. Line 2 sets the axis limits for the x and y axes of the plot window. The axis limits can be set at any time, even after the plot is drawn. It’s equivalent to changing the size of a window looking at the plot and gives you the ability to zoom in or out on different regions if you want. Line 3 turns the hold on, this way any plotting commands that are issued will cause the plotting to be on the same plot. Line 4 plots a box on the graph and line 5 places the text string “Click inside box to quit” inside the box that was plotted, placing the beginning of the text at (1, 1.6). Line 5 starts a while loop that terminates with the second “end” statement. Since the condition of the while loop is “1”, it will operate forever, thus the only way to exit the while loop and terminate the program is to satisfy the final “if” condition within the loop which causes the “break” to execute and the while loop to terminate. Inside the while loop, on line 6, the Matlab function ginput () is used. It returns the x and y coordinates on the plot where the mouse button was clicked as well as which mouse button was clicked. Line 7 is an “if” statement that checks to see if mouse button 1 was clicked. If so, a red “+” is plotted on the graph at the (x,y) location where the mouse click was read. The “end” statement on the line ends this “if” condition. Line 8 is an “if” statement that checks to see if mouse button 2 was clicked. If so, a yellow “o” is plotted on the graph at the (x,y) location where the mouse click was read. The “end” statement on the line ends this “if” condition. Line 9 is an “if” statement that checks to see if mouse button 3 was clicked. If so, a green “*” is plotted on the graph at the (x,y) location where the mouse click was read. The “end” statement on the line ends this “if” condition. Line 10 is the final “if” condition. It checks to see if the (x,y) coordinates of mouse click fall within 1&lt;x&lt;2 and 2&lt;y&lt;3, which are the limits of the text box. If so, then the “break” is executed and the while loop ends. Line 11 is the “end” statement for line 10. Line 12 is the “end” statement for the while loop. Line 13 turns off the plot hold, thus allowing multiple plot windows to be opened again.
  7. Instructor notes: Now that we’ve seen a script file, we’re going to move to function files. Function files in Matlab are very much like functions in C/C++. The key difference between function files and script files is that variables in function files are local. Any variables that are used within a function file need to be specified within the function or passed in as arguments in the argument list. You may want to point out the similarities between C/C++ functions and Matlab function files. One difference between the two is that while a C/C++ function can only “return” one value, Matlab functions can return as many as desired. The function file should have the same name as the function itself with the “.m” extension added to it. Unlike C/C++ functions which can only be called from within a program, Matlab function files can be called directly from the command window, from a script file, or from another function file.
  8. Instructor notes: This first bullet points out the reason that variables inside of function files are local and not known to the command window is that executing a function file causes control to switch out of the Matlab workspace into the function file’s workspace. As the second and third bullet points indicate, the function file is not part of the Matlab workspace and therefore those variables that exist within the function file and their corresponding values are not known to the command window when control is returned from the function file. In order to transfer the values of desired variables back to the Matlab workspace, they must be passed back according to the function call syntax. What this boils down to is that variables that are being passed into the function need to appear in parentheses to the right of the function name during the function call and variables that are being passed back from the function to the Matlab workspace must appear in square brackets to the left of the equals sign in the function call and function definition.
  9. Instructor notes: Most of the information on this slide has been previewed on the previous slide. Arguments that are going into the function appear within parentheses to the right of the function name when the function is called. This is how you would get variables from the Matlab workspace or another function file into the called function. Values that are being determined within the function and returned by the function appear in square brackets prior to the equal sign on the line on which the function is called. These values will be returned by the function back to the Matlab workspace of the workspace of another function if this function were called within another function. Just as in C/C++, it’s the value of the variables that’s being passed. Addresses are NOT passed between workspaces.
  10. Instructor notes: Using the same variable names in the return list of a Matlab function call as in the argument list has the effect of assigning new values to those variables.. This is a key idea to get across.
  11. Instructor notes: Here we have an example of a swap function that has the same variables in its argument list as it does in its returned values list. In this example a and b are passed into the function. Within the function, temp is assigned a’s value, a is assigned b’s value and temp, which is a’s original value, is assigned to b. So, by the end of swap, the values of a and b have been swapped. Then, the swapped a and b are returned. To actually have the swap of a and b have an effect in the workspace that called swap requires that in the call to the function, the same variables were used in the calling “return” list and the calling “argument” list. A side note here…the comments that occur immediately after the first line of the function definition will be displayed in the command window if the user types help function_name at the command prompt. So, in this example, if the user were, at the command prompt, to type help swap, then the six comment lines that appear in the function definition above, would be displayed in the command window.
  12. Instructor notes: Here we see the result of calling the swap function. Note that the variables in the function call do not have to be a and b, since a and b are local to the function definition. What is necessary is that the variables in square brackets and in parentheses have the same name. When called with initial values of x=5 and y=6, swap switches the values of x and y in the calling workspace. Hopefully some carryover from C/C++ explanation of functions will help out here, but this is somewhat of an abstract point to get a grasp of and quite possibly should be gone over slowly on the board or with an example that demonstrates visually what is taking place. It is slightly different than what happens in the C/C++ examples of swap.
  13. Instructor notes: As quickly mentioned on an earlier slide, when entering help function_name at the cojmmand prompt, the comment information that appears immediately beneath the first line of the function will be displayed as help information in the command window.
  14. Instructor notes: A heads up for the students and a quick reminder…the Matlab function that is being called must exist in the current working directory, or be in a directory that is specified as part of Matlab’s default search path, otherwise Matlab will not be able to find the function and will return an error message. Not finding the function and finding the function but with a “signature” that does not match that of the function file, will result in an error message. That error message may be somewhat obtuse and may be along the lines of that given in the slide. So, it’s a good idea for both student and instructors to be on the lookout for error messages that do not appear to have anything to do with the problem at hand.
  15. Instructor notes: A reminder to make sure you change your working directory to the directory in which the function file exists prior to executing the function file. Either the cd or chdir commands can be used, as well as the icons at the top of the command window.
  16. Instructor notes: As the slide indicates, Matlab is more flexible in dealing with variables changing their data types on the fly than C would be. All that is required to change the data type of a variable, is to assign the variable to a new value. After having gotten used to the strict data typing of C this might take students some practice to get used to.
  17. Instructor notes: Here we see the factorial function. It takes in argument “k” and returns value “n”. The main point here is that if k is less than zero, the factorial cannot be computed and n is assigned a string error message as its value. Otherwise, if the factorial can be computed, n is assigned the value of the factorial. So, on the fly Matlab is able to handle assigning to the same variable, different types of values.