This document provides a summary of a course on introduction to MATLAB. The course includes 7 lectures covering topics like variables, operations, plotting, visualization, programming, solving equations and advanced methods. It will have problem sets to be submitted after each lecture and requirements to pass include attending all lectures and completing all problem sets. The course materials provide an overview of MATLAB including getting started, creating and manipulating variables, and basic plotting.
A short term course on Matlab for Beginners. It gives an insight of the basic commands used for Matlab programming. This course is useful for them who have no prior knowledge in Matlab programming and want to their projects bases on Matlab.
A short term course on Matlab for Beginners. It gives an insight of the basic commands used for Matlab programming. This course is useful for them who have no prior knowledge in Matlab programming and want to their projects bases on Matlab.
Functions, Exception, Modules and Files
Functions: Difference between a Function and a Method, Defining a Function, Calling a Function, Returning Results from a Function, Returning Multiple Values from a Function, Functions are First Class Objects, Pass by Object Reference, Formal and Actual Arguments, Positional Arguments, Keyword Arguments, Default Arguments, Variable Length Arguments, Local and Global Variables, The Global Keyword, Passing a Group of Elements to a Function, Recursive Functions, Anonymous Functions or Lambdas (Using Lambdas with filter() Function, Using Lambdas with map() Function, Using Lambdas with reduce() Function), Function Decorators, Generators, Structured Programming, Creating our Own Modules in Python, The Special Variable __name__
Exceptions: Errors in a Python Program (Compile-Time Errors, Runtime Errors, Logical Errors),Exceptions, Exception Handling, Types of Exceptions, The Except Block, The assert Statement, UserDefined Exceptions, Logging the Exceptions
20%
Files: Files, Types of Files in Python, Opening a File, Closing a File, Working with Text Files Containing Strings, Knowing Whether a File Exists or Not, Working with Binary Files, The with Statement, Pickle in Python, The seek() and tell() Methods, Random Accessing of Binary Files, Random Accessing of Binary Files using mmap, Zipping and Unzipping Files, Working with Directories, Running Other Programs from Python Program
In MATLAB, a vector is created by assigning the elements of the vector to a variable. This can be done in several ways depending on the source of the information.
—Enter an explicit list of elements
—Load matrices from external data files
—Using built-in functions
—Using own functions in M-files
Functions, Exception, Modules and Files
Functions: Difference between a Function and a Method, Defining a Function, Calling a Function, Returning Results from a Function, Returning Multiple Values from a Function, Functions are First Class Objects, Pass by Object Reference, Formal and Actual Arguments, Positional Arguments, Keyword Arguments, Default Arguments, Variable Length Arguments, Local and Global Variables, The Global Keyword, Passing a Group of Elements to a Function, Recursive Functions, Anonymous Functions or Lambdas (Using Lambdas with filter() Function, Using Lambdas with map() Function, Using Lambdas with reduce() Function), Function Decorators, Generators, Structured Programming, Creating our Own Modules in Python, The Special Variable __name__
Exceptions: Errors in a Python Program (Compile-Time Errors, Runtime Errors, Logical Errors),Exceptions, Exception Handling, Types of Exceptions, The Except Block, The assert Statement, UserDefined Exceptions, Logging the Exceptions
20%
Files: Files, Types of Files in Python, Opening a File, Closing a File, Working with Text Files Containing Strings, Knowing Whether a File Exists or Not, Working with Binary Files, The with Statement, Pickle in Python, The seek() and tell() Methods, Random Accessing of Binary Files, Random Accessing of Binary Files using mmap, Zipping and Unzipping Files, Working with Directories, Running Other Programs from Python Program
In MATLAB, a vector is created by assigning the elements of the vector to a variable. This can be done in several ways depending on the source of the information.
—Enter an explicit list of elements
—Load matrices from external data files
—Using built-in functions
—Using own functions in M-files
MATLAB's anonymous functions provide an easy way to specify a function. An anonymous function is a function defined without using a separate function file. It is a MATLAB feature that lets you define a mathematical expression of one or more inputs and either assign that expression to a function. This method is good for relatively simple functions that will not be used that often and that can be written in a single expression.
The inline command lets you create a function of any number of variables by giving a string containing the function followed by a series of strings denoting the order of the input variables. It is similar to an Anonymous Function
Previous post we discussed what is a user defined function in MATLAB. This lecture we will discuss how to define a function and how to call the function in a script.
Components of a function is discussed in the previous lecture. The first statement in a function must be function definition.The basic syntax of a function definition is:
function[a, b, c]= basicmath(x,y)
Basically a function accepts an input vector, perform the operation, and returns a result. The sample function given has two input variables and three output variables. But we can also have functions without input or/and output.
In this lecture we will discuss about another flow control method – Loop control.
A loop control is used to execute a set of commands repeatedly
The set of commands is called the body of the loop
MATLAB has two loop control techniques
Counted loops - executes commands a specified number of times
Conditional loops - executes commands as long as a specified expression is true
User-defined functions are similar to the MATLAB pre-defined functions. A function is a MATLAB program that can accept inputs and produce outputs. A function can be called or executed by another program or function.
Code for a function is done in an Editor window or any text editor same way as script and saved as m-file. The m-file must have the same name as the function.
A MATLAB function that accepts another function as an input is called a function function. Function handles are used for passing functions to function functions. Syntax for function function is same as simple functions, but one or more input arguments will be function handles.
Multiple functions within one function file is called local function. Name of function file should be name of main function. Main function can be called from the command window or any other function. Local functions are typed in any order after the main function. Local functions are only visible to other functions in the same file.
A private function is a function residing in a sub directory with the name private. Private functions are visible only to functions in the parent directory.
Polynomials are very important mathematical tool for Engineers. In this lecture we will discuss about how to deal with Polynomials in MATLAB and one of its application, Curve Fitting.
A Powerpoint Presentation designed to provide beginners to MATLAB an introduction to the MATLAB environment and introduce them to the fundamentals of MATLAB including matrix generation and manipulation, Arrays, MATLAB Graphics, Data Import and Export, etc
Introduction to programming in MATLAB
Youtube: https://www.youtube.com/watch?v=gDhpqj13dTA
Github: https://github.com/Mustafa-nafaa/Multimedia-TechnologyLab/tree/main/Week1:Introduction%20Matlab
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Welocme to ViralQR, your best QR code generator.ViralQR
Welcome to ViralQR, your best QR code generator available on the market!
At ViralQR, we design static and dynamic QR codes. Our mission is to make business operations easier and customer engagement more powerful through the use of QR technology. Be it a small-scale business or a huge enterprise, our easy-to-use platform provides multiple choices that can be tailored according to your company's branding and marketing strategies.
Our Vision
We are here to make the process of creating QR codes easy and smooth, thus enhancing customer interaction and making business more fluid. We very strongly believe in the ability of QR codes to change the world for businesses in their interaction with customers and are set on making that technology accessible and usable far and wide.
Our Achievements
Ever since its inception, we have successfully served many clients by offering QR codes in their marketing, service delivery, and collection of feedback across various industries. Our platform has been recognized for its ease of use and amazing features, which helped a business to make QR codes.
Our Services
At ViralQR, here is a comprehensive suite of services that caters to your very needs:
Static QR Codes: Create free static QR codes. These QR codes are able to store significant information such as URLs, vCards, plain text, emails and SMS, Wi-Fi credentials, and Bitcoin addresses.
Dynamic QR codes: These also have all the advanced features but are subscription-based. They can directly link to PDF files, images, micro-landing pages, social accounts, review forms, business pages, and applications. In addition, they can be branded with CTAs, frames, patterns, colors, and logos to enhance your branding.
Pricing and Packages
Additionally, there is a 14-day free offer to ViralQR, which is an exceptional opportunity for new users to take a feel of this platform. One can easily subscribe from there and experience the full dynamic of using QR codes. The subscription plans are not only meant for business; they are priced very flexibly so that literally every business could afford to benefit from our service.
Why choose us?
ViralQR will provide services for marketing, advertising, catering, retail, and the like. The QR codes can be posted on fliers, packaging, merchandise, and banners, as well as to substitute for cash and cards in a restaurant or coffee shop. With QR codes integrated into your business, improve customer engagement and streamline operations.
Comprehensive Analytics
Subscribers of ViralQR receive detailed analytics and tracking tools in light of having a view of the core values of QR code performance. Our analytics dashboard shows aggregate views and unique views, as well as detailed information about each impression, including time, device, browser, and estimated location by city and country.
So, thank you for choosing ViralQR; we have an offer of nothing but the best in terms of QR code services to meet business diversity!
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
2. 6.094
Introduction to Programming in MATLAB®
Lecture 1: Variables, Operations, and
Plotting
Sourav Dey
Danilo Šćepanović
Ankit Patel
Patrick Ho
IAP 2009
4. Course Layout
• Problem Sets / Office Hours
One per day, should take about 3 hours to do
Submit doc or pdf (include pertinent code)
• Requirements for passing
Attend all lectures
Complete all problem sets (FAIL, Check or +)
• Prerequisites
Basic familiarity with programming
Basic linear algebra, differential equations, and
probability
5. Outline
(1) Getting Started
(2) Making Variables
(3) Manipulating Variables
(4) Basic Plotting
6. Getting Started
• To get MATLAB Student Version for yourself
» https://msca.mit.edu/cgi-bin/matlab
Use VPN client to enable off-campus access
Note: MIT certificates are required
• Open up MATLAB for Windows
Through the START Menu
• On Athena
» add matlab
» matlab &
7. Current directory
Workspace
Command Window
Command History
Courtesy of The MathWorks, Inc. Used with permission.
8. Customization
• File Preferences
Allows you personalize your MATLAB experience
Courtesy of The MathWorks, Inc. Used with permission.
9. MATLAB Basics
• MATLAB can be thought of as a super-powerful
graphing calculator
Remember the TI-83 from calculus?
With many more buttons (built-in functions)
• In addition it is a programming language
MATLAB is an interpreted language, like
Scheme
Commands executed line by line
10. Conversing with MATLAB
• who
MATLAB replies with the variables in your workspace
• what
MATLAB replies with the current directory and
MATLAB files in the directory
• why
• help
The most important function for learning MATLAB on
your own
More on help later
11. Outline
(1) Getting Started
(2) Making Variables
(3) Manipulating Variables
(4) Basic Plotting
12. Variable Types
• MATLAB is a weakly typed language
No need to initialize variables!
• MATLAB supports various types, the most often used are
» 3.84
64-bit double (default)
» ‘a’
16-bit char
• Most variables you’ll deal with will be arrays or matrices of
doubles or chars
• Other types are also supported: complex, symbolic, 16-bit
and 8 bit integers, etc.
13. Naming variables
• To create a variable, simply assign a value to a name:
» var1=3.14
» myString=‘hello world’
• Variable names
first character must be a LETTER
after that, any combination of letters, numbers and _
CASE SENSITIVE! (var1 is different from Var1)
• Built-in variables
i and j can be used to indicate complex numbers
pi has the value 3.1415926…
ans stores the last unassigned value (like on a calculator)
Inf and -Inf are positive and negative infinity
NaN represents ‘Not a Number’
14. Hello World
• Here are several flavors of Hello World to introduce MATLAB
• MATLAB will display strings automatically
» ‘Hello 6.094’
• To remove “ans =“, use disp()
» disp('Hello 6.094')
• sprintf() allows you to mix strings with variables
» class=6.094;
» disp(sprintf('Hello %g', class))
The format is C-syntax
15. Scalars
• A variable can be given a value explicitly
» a = 10
shows up in workspace!
• Or as a function of explicit values and existing variables
» c = 1.3*45-2*a
• To suppress output, end the line with a semicolon
» cooldude = 13/3;
16. Arrays
• Like other programming languages, arrays are an
important part of MATLAB
• Two types of arrays
(1) matrix of numbers (either double or complex)
(2) cell array of objects (more advanced data structure)
MATLAB makes vectors easy!
That’s its power!
17. Row Vectors
• Row vector: comma or space separated values between
brackets
» row = [1 2 5.4 -6.6];
» row = [1, 2, 5.4, -6.6];
• Command window:
• Workspace:
Courtesy of The MathWorks, Inc. Used with permission.
18. Column Vectors
• Column vector: semicolon separated values between
brackets
» column = [4;2;7;4];
• Command window:
• Workspace:
Courtesy of The MathWorks, Inc. Used with permission.
19. Matrices
• Make matrices like vectors
⎡1 2⎤
• Element by element a=⎢
» a= [1 2;3 4]; ⎣3 4⎥
⎦
• By concatenating vectors or matrices (dimension matters)
» a = [1 2];
» b = [3 4];
» c = [5;6];
» d = [a;b];
» e = [d c];
» f = [[e e];[a b a]];
20. save/clear/load
• Use save to save variables to a file
» save myfile a b
saves variables a and b to the file myfile.mat
myfile.mat file in the current directory
Default working directory is
» MATLABwork
Create own folder and change working directory to it
» MyDocuments6.094day1
• Use clear to remove variables from environment
» clear a b
look at workspace, the variables a and b are gone
• Use load to load variable bindings into the environment
» load myfile
look at workspace, the variables a and b are back
• Can do the same for entire environment
» save myenv; clear all; load myenv;
21. Exercise: Variables
• Do the following 5 things:
Create the variable r as a row vector with values 1 4
7 10 13
Create the variable c as a column vector with values
13 10 7 4 1
Save these two variables to file varEx
clear the workspace
load the two variables you just created
» r=[1 4 7 10 13];
» c=[13; 10; 7; 4; 1];
» save varEx r c
» clear r c
» load varEx
22. Outline
(1) Getting Started
(2) Making Variables
(3) Manipulating Variables
(4) Basic Plotting
23. Basic Scalar Operations
• Arithmetic operations (+,-,*,/)
» 7/45
» (1+i)*(2+i)
» 1 / 0
» 0 / 0
• Exponentiation (^)
» 4^2
» (3+4*j)^2
• Complicated expressions, use parentheses
» ((2+3)*3)^0.1
• Multiplication is NOT implicit given parentheses
» 3(1+0.7) gives an error
• To clear cluttered command window
» Clc
24. Built-in Functions
• MATLAB has an enormous library of built-in functions
• Call using parentheses – passing parameter to function
» sqrt(2)
» log(2), log10(0.23)
» cos(1.2), atan(-.8)
» exp(2+4*i)
» round(1.4), floor(3.3), ceil(4.23)
» angle(i); abs(1+i);
25. Help/Docs
• To get info on how to use a function:
» help sin
Help contains related functions
• To get a nicer version of help with examples and easy-to-
read descriptions:
» doc sin
• To search for a function by specifying keywords:
» doc + Search tab
» lookfor hyperbolic
One-word description of what
you're looking for
26. Exercise: Scalars
• Verify that e^(i*x) = cos(x) + i*sin(x) for a few values of x.
» x = pi/3;
» a = exp(i*x)
» b = cos(x)+ i*sin(x)
» a-b
27. size & length
• You can tell the difference between a row and a column
vector by:
Looking in the workspace
Displaying the variable in the command window
Using the size function
• To get a vector's length, use the length function
28. transpose
• The transpose operators turns a column vector into a row
vector and vice versa
» a = [1 2 3 4]
» transpose(a)
• Can use dot-apostrophe as short-cut
» a.'
• The apostrophe gives the Hermitian-transpose, i.e.
transposes and conjugates all complex numbers
» a = [1+j 2+3*j]
» a'
» a.'
• For vectors of real numbers .' and ' give same result
29. Addition and Subtraction
• Addition and subtraction are element-wise; sizes must
match (unless one is a scalar):
[12 3 32 −11] ⎡ 12 ⎤ ⎡ 3 ⎤ ⎡ 9 ⎤
⎢ 1 ⎥ ⎢ −1⎥ ⎢ 2 ⎥
+ [ 2 11 −30 32] ⎢ ⎥−⎢ ⎥ = ⎢ ⎥
⎢ −10 ⎥ ⎢13 ⎥ ⎢ −23⎥
= [14 14 2 21] ⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎣ 0 ⎦ ⎣33⎦ ⎣ −33⎦
• The following would give an error
» c = row + column
• Use the transpose to make sizes compatible
» c = row’ + column
» c = row + column’
• Can sum up or multiply elements of vector
» s=sum(row);
» p=prod(row);
30. Element-Wise Functions
• All the functions that work on scalars also work on vectors
» t = [1 2 3];
» f = exp(t);
is the same as
» f = [exp(1) exp(2) exp(3)];
• If in doubt, check a function’s help file to see if it handles
vectors elementwise
• Operators (* / ^) have two modes of operation
element-wise
standard
32. Operators: standard
• Multiplication can be done in a standard way or element-wise
• Standard multiplication (*) is either a dot-product or an outer-
product
Remember from linear algebra: inner dimensions must MATCH!!
• Standard exponentiation (^) implicitly uses *
Can only be done on square matrices or scalars
• Left and right division (/ ) is same as multiplying by inverse
Our recommendation: just multiply by inverse (more on this
later)
⎡ 4⎤ ⎡1 2 ⎤ ⎡1 2 ⎤ ⎡1 2 ⎤ ⎡1 1 1⎤ ⎡1 2 3⎤ ⎡3 6 9 ⎤
[1 2 3]* ⎢ 2⎥ = 11
⎢ ⎥
⎢3 4 ⎥
⎣ ⎦
^2=⎢ ⎥ * ⎢3 4 ⎥
⎣3 4 ⎦ ⎣ ⎦
⎢2 2 2⎥ * ⎢1 2 3⎥ = ⎢6 12 18 ⎥
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢1 ⎥
⎣ ⎦ Must be square to do powers ⎢3 3 3⎥ ⎢1 2 3⎥ ⎢9 18 27⎥
⎣ ⎦ ⎣ ⎦ ⎣ ⎦
1× 3* 3 ×1 = 1× 1 3 × 3* 3 × 3 = 3 × 3
33. Exercise: Vector Operations
• Find the inner product between [1 2 3] and [3 5 4]
» a=[1 2 3]*[3 5 4]’
• Multiply the same two vectors element-wise
» b=[1 2 3].*[3 5 4]
• Calculate the natural log of each element of the resulting
vector
» c=log(b)
34. Automatic Initialization
• Initialize a vector of ones, zeros, or random numbers
» o=ones(1,10)
row vector with 10 elements, all 1
» z=zeros(23,1)
column vector with 23 elements, all 0
» r=rand(1,45)
row vector with 45 elements (uniform [0,1])
» n=nan(1,69)
row vector of NaNs (useful for representing uninitialized
variables)
The general function call is:
var=zeros(M,N);
Number of rows Number of columns
35. Automatic Initialization
• To initialize a linear vector of values use linspace
» a=linspace(0,10,5)
starts at 0, ends at 10 (inclusive), 5 values
• Can also use colon operator (:)
» b=0:2:10
starts at 0, increments by 2, and ends at or before 10
increment can be decimal or negative
» c=1:5
if increment isn’t specified, default is 1
• To initialize logarithmically spaced values use logspace
similar to linspace
36. Exercise: Vector Functions
• Make a vector that has 10,000 samples of
f(x) = e^{-x}*cos(x), for x between 0 and 10.
» x = linspace(0,10,10000);
» f = exp(-x).*cos(x);
37. Vector Indexing
• MATLAB indexing starts with 1, not 0
We will not respond to any emails where this is the
problem.
• a(n) returns the nth element
[13 5 9 10]
a(1) a(2) a(3) a(4)
• The index argument can be a vector. In this case, each
element is looked up individually, and returned as a vector
of the same size as the index vector.
» x=[12 13 5 8];
» a=x(2:3); a=[13 5];
» b=x(1:end-1); b=[12 13 5];
38. Matrix Indexing
• Matrices can be indexed in two ways
using subscripts (row and column)
using linear indices (as if matrix is a vector)
• Matrix indexing: subscripts or linear indices
b(1,1) ⎡14 33⎤ b(1,2) b(1) ⎡14 33⎤ b(3)
b(2,1)
⎢9 8⎥ b(2,2) b(2)
⎢9 8⎥ b(4)
⎣ ⎦ ⎣ ⎦
• Picking submatrices
» A = rand(5) % shorthand for 5x5 matrix
» A(1:3,1:2) % specify contiguous submatrix
» A([1 5 3], [1 4]) % specify rows and columns
39. Advanced Indexing 1
• The index argument can be a matrix. In this case, each
element is looked up individually, and returned as a matrix
of the same size as the index matrix.
» a=[-1 10 3 -2]; ⎡ −1 10 −2 ⎤
b=⎢ ⎥
» b=a([1 2 4;3 4 2]); ⎣ 3 −2 10 ⎦
• To select rows or columns of a matrix, use the :
⎡12 5 ⎤
c=⎢
⎣ −2 13⎥
⎦
» d=c(1,:); d=[12 5];
» e=c(:,2); e=[5;13];
» c(2,:)=[3 6]; %replaces second row of c
40. Advanced Indexing 2
• MATLAB contains functions to help you find desired values
within a vector or matrix
» vec = [1 5 3 9 7]
• To get the minimum value and its index:
» [minVal,minInd] = min(vec);
• To get the maximum value and its index:
» [maxVal,maxInd] = max(vec);
• To find any the indices of specific values or ranges
» ind = find(vec == 9);
» ind = find(vec > 2 & vec < 6);
find expressions can be very complex, more on this later
• To convert between subscripts and indices, use ind2sub,
and sub2ind. Look up help to see how to use them.
41. Exercise: Vector Indexing
• Evaluate a sine wave at 1,000 points between 0 and 2*pi.
• What’s the value at
Index 55
Indices 100 through 110
• Find the index of
the minimum value,
the maximum value, and
values between -0.001 and 0.001
» x = linspace(0,2*pi,1000);
» y=sin(x);
» y(55)
» y(100:110)
» [minVal,minInd]=min(y)
» [maxVal,maxInd]=max(y)
» inds=find(y>-0.001 & y<0.001)
42. BONUS Exercise: Matrices
• Make a 3x100 matrix of zeros, and a vector x that has 100 values
between 0 and 10
» mat=zeros(3,100);
» x=linspace(0,10,100);
• Replace the first row of the matrix with cos(x)
» mat(1,:)=cos(x);
• Replace the second row of the matrix with log((x+2)^2)
» mat(2,:)=log((x+2).^2);
• Replace the third row of the matrix with a random vector of the
correct size
» mat(3,:)=rand(1,100);
• Use the sum function to compute row and column sums of mat
(see help)
» rs = sum(mat,2);
» cs = sum(mat); % default dimension is 1
43. Outline
(1) Getting Started
(2) Making Variables
(3) Manipulating Variables
(4) Basic Plotting
44. Plotting Vectors
• Example
» x=linspace(0,4*pi,10);
» y=sin(x);
• Plot values against their index
» plot(y);
• Usually we want to plot y versus x
» plot(x,y);
MATLAB makes visualizing data
fun and easy!
45. What does plot do?
• plot generates dots at each (x,y) pair and then connects the dots
with a line
• To make plot of a function look smoother, evaluate at more points
» x=linspace(0,4*pi,1000);
» plot(x,sin(x));
• x and y vectors must be same size or else you’ll get an error
» plot([1 2], [1 2 3])
error!!
1 1
10 x values: 0.8
0.6
1000 x values:
0.8
0.6
0.4 0.4
0.2 0.2
0 0
-0.2 -0.2
-0.4 -0.4
-0.6 -0.6
-0.8 -0.8
-1 -1
0 2 4 6 8 10 12 14 0 2 4 6 8 10 12 14
46. Plot Options
• Can change the line color, marker style, and line style by
adding a string argument
» plot(x,y,’k.-’);
color marker line-style
• Can plot without connecting the dots by omitting line style
argument
» plot(x,y,’.’)
• Look at help plot for a full list of colors, markers, and
linestyles
47. Other Useful plot Commands
• Much more on this in Lecture 2, for now some simple
commands
• To plot two lines on the same graph
» hold on;
• To plot on a new figure
» figure;
» plot(x,y);
• Play with the figure GUI to learn more
add axis labels
add a title
add a grid
zoom in/zoom out
48. Exercise: Plotting
• Plot f(x) = e^x*cos(x) on the interval x = [0 10]. Use a red
solid line with a suitable number of points to get a good
resolution.
» x=0:.01:10;
» plot(x,exp(x).*cos(x),’r’);
49. End of Lecture 1
(1) Getting Started
(2) Making Variables
(3) Manipulating Variables
(4) Basic Plotting
Hope that wasn’t too much!!