New Microsoft Word Document

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 40

You can execute commands by entering them in the command window after the MATLAB prompt (>>)

and pressing the Enter key.


TASK
Multiply the numbers 3 and 5 together with the command 3*5

Unless otherwise specified, MATLAB stores calculations in a variable named 


ans
.

>> 7 + 3
ans =
10
TASK
Assign the 3*5 calculation to a variable named m as shown:

m = 3*5

he equals sign (=) in MATLAB is the assignment operator, meaning that the expression on the right of
the equals sign is assigned to the variable on the left.

When you enter x = 3 + 4, MATLAB first evaluates 3 + 4 and then assigns the result (7) to the
variable x.
TASK
Enter the command m = m + 1 to see what happens.

Notice that the Workspace window (on the right) shows all the variables currently in the workspace.

TASK
Create a variable named y that has the value m/2.

When you enter a command without a semicolon at the end, MATLAB displays the result in the
command prompt.

>> x = 5 + 1
x =
6

If you add a semicolon to the end of a command, the result will not be displayed. The command will
still be executed, as you can see in the workspace.
>> x = 5 + 1;
TASK
Enter k = 8 - 2; with a semicolon at the end.

The result won't appear in the command prompt, but you can see the value in the Workspace window.

You can recall previous commands by pressing the Up arrow key on your keyboard. Note that the Command
Window must be the active window for this to work.
TASK
Press the Up arrow to return to the command m = 3*5 and edit the command to be m = 3*k
Hint
See Solution
Task 7
Further Practice

When you enter just a variable name at the command prompt, MATLAB returns the current value of
that variable.
TASK
The value of y was calculated using m. Was y recalculated when m was modified?

Enter just the variable name y at the command prompt (and press Enter).

The value of y was unchanged because MATLAB does not rerun previous commands in the
Command Window.

If you want to recalculate y after m is modified, you need to repeat the command y = m/2.

Try this now! Use the Up arrow to recall the command y = m/2, then press Enter. To see the new
value of y, remember not to use a semicolon at the end of the command.
You can name your MATLAB variables anything you'd like as long as they start with a letter and contain only
letters, numbers, and underscores (_).

MATLAB variables are also case sensitive.


TASK
Assign the value -2 to the variable A.
Hint
See Solution
Task 2
Further Practice

Notice that the variables a and A both exist in the workspace.

You can name all your variables a or x, but it is more useful to name your variables something
meaningful.
TASK
Calculate 

a+A2
. Assign the result to the variable avgAa.

If you use an invalid variable name, MATLAB will display a suggested correction. You can use this
command, modify it, or press Esc to delete the suggestion.

Try creating the variable 3sq = 9 to demonstrate this behavior.


You can save variables in your workspace to a MATLAB specific file format called a MAT-file using
the save command.

To save the workspace to a MAT-file named filename.mat, use the command:

>> save filename


TASK
Save the workspace variable to a file named datafile.mat

When you switch to a new problem in MATLAB, you might want to tidy up your workspace. You can
remove all variables from your workspace with the clear function.
TASK
Use clear to empty the workspace.

On the right-hand side of the screen, look at the workspace. You can see that clear removed all the variables.

You can load variables from a MAT-file using the load command.

>> load filename


TASK
Load the variables from the file datafile.mat.

Go to task
Task 4
Task 5
Further Practice

Notice that the variable data is listed in the workspace. You can see contents of any variable by
entering the name of the variable.

>> myvar
TASK
Display the contents of the variable data.
The clear function cleans up the workspace. You can use the clc command to clean up
the Command Window.
TASK
Clear the command window using the clc command.

When you close MATLAB, the workspace will be cleared. MAT-files can be used to save your variables. The
variables can then be loaded into the workspace when you reopen MATLAB.

If you want to load or save only some of your variables, you can use two inputs to the functions.

The file myData.mat contains multiple variables. It was previously created for this further practice. Try
loading just the variable k:

>> load myData k

Then try saving the variable k to a new MAT-file called justk.mat:

>> save justk k


Next section >
MATLAB contains built-in constants, such as pi to represent 
π
.

>> a = pi
a =
3.1416

Also, although only four decimal places are shown for 


π
, it is represented internally with greater precision.
TASK
Create a variable called x with a value of 
π/2
.

MATLAB contains a wide variety of built-in functions, such as abs (absolute value)


and eig (calculate eigenvalues).

>> a = sin(-5)
a =
0.9589

Note that MATLAB uses parentheses to pass inputs to functions, similar to standard mathematical
notation.
TASK
Use the sin function to calculate the sine of x. Assign the result to a variable named y.

Use the sqrt function to calculate the square root of -9. Assign the result to a variable named z.

Note that the solution contains the imaginary number, i, which is a built-in constant in MATLAB.

Only the first four decimal places are displayed in the Command Window. You can control the
displayed precision with the format function.

Try entering format long. Then try displaying the value of x.

Enter format short to switch back to the default display.


>> format long

>> z
3.2 The MATLAB Editor

You can enter commands in a script by clicking on the gray code box.

When you're ready, you can submit your code by clicking the blue Submit button.
TASK
Enter the command r = 3 in the script.
Hint
See Solution Submit
Reset
Task 2
Further Practice
WORKSPACE

TASK
Add the command x = pi*r^2 to the script.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does x exist?
Does x have the correct value?

When you complete tasks in the Live Editor, the Command Window and Workspace are minimized.

You can still access them by clicking on their name.

Try viewing the variables x and r in the Workspace by clicking Workspace on the right.


3.3 Running Scripts

This live script contains formatted text, code, and section breaks. In this course, scripts will
include Task headers to show where you should enter your code.

You can test your code before submitting by running the script. To execute the entire script, click
the Run button.
TASK
Run the script to populate the output pane.

Then modify the command for Task 1 so that r has a value of 0.5.


Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does r have the correct value?
Does x have the correct value?

To execute the code for just one section, you can click the Run Section button in the MATLAB
Toolstrip.

Try changing the value of r and running only that section. What happens to the value of r in the
output pane? What about the value of x?

You can also use the buttons in the Toolstrip to switch between text and code.

Try adding the text "Calculate circumference." Add a new code block after the text that
contains y = 2*pi*r.
4.1 Manually Entering Arrays

What's an Array?

All MATLAB variables are arrays. This means that each numeric variable can contain multiple
numbers. You can use arrays to store related data in one variable.

Because you'll use arrays every time you program, it's important to get to know them and the
terminology used to describe them.
A single number, called a scalar, is actually a 1-by-1 array, meaning it contains 1 row and 1 column.
TASK
Create a variable named x with a value of 4.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is x assigned correctly?

You can create arrays with multiple elements using square brackets.

x = [3 5]
x =
3 5
TASK
Create an array named x with two elements: 7 and 9
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does x have two elements?
Does x have the correct values?

When you separate numbers by spaces (or commas) as shown in the previous task, MATLAB
combines the numbers into a row vector, which is an array with one row and multiple columns (1-by-
n). When you separate numbers by semicolons, MATLAB creates a column vector (n-by-1).

x = [1;3]
x =
1
3
TASK
Create an array named x with two elements, 7 and 9, in a single column.

Try copying the previous command and changing the space between the numbers to a semicolon (;).

Create a row vector named x that contains the values 3, 10, and 5 in that order.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does x have three elements?
Is x a row vector?
Does x have the correct values?

TASK
Create a column vector named x that contains the values 8, 2, and -4 in that order.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does x have three elements?
Is x a column vector?
Does x have the correct values?

You can combine spaces and semicolons to create a matrix, which is an array with multiple rows and
columns. When entering a matrix, you must enter them row by row.

x = [3 4 5;6 7 8]
x =
3 4 5
6 7 8
TASK
Create a matrix named x with the values shown below.

5 6 7
8 9 10
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does x have the correct size?
Does x have the correct values?

In MATLAB, you can perform calculations within the square brackets.

x = [abs(-4) 4^2]
x =
4 16
TASK
Create a row vector named x that contains sqrt(10) as its first element and pi^2 (
π2
) as its second element.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does x have the correct size?
Does x have the correct values?

Arrays are used throughout MATLAB. In fact, MATLAB is an abbreviation for MATrix LABoratory.
You'll find that most MATLAB functionality can work on multiple values at once.

There is some flexibility when you create arrays. For example, these are all valid ways to create the
same array:

x = [7 9]
x=[7,9]
x = [7, 9]

Try experimenting with whitespace, commas, and semicolons when creating this matrix:
7;4;10 1;5;4 8;8;2
4.2 Creating Evenly-Spaced Vectors

It is common to create vectors containing evenly-spaced numbers, such as the vector below.

y = [5 6 7 8]
y =
5 6 7 8
TASK
Create a row vector named x that contains the values 1, 2, and 3, in that order.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does x have three elements?
Does x have the correct values?

For long vectors, entering individual numbers is not practical. An alternative, shorthand method for
creating evenly-spaced vectors is to use the : operator and specify only the start and end points.

y = 5:8
y =
5 6 7 8

Notice that square brackets are not needed when you use the colon operator.
TASK
Create a row vector named x with the values 1, 2, 3, and 4, but this time using the : operator.

For long vectors, entering individual numbers is not practical. An alternative, shorthand method for
creating evenly-spaced vectors is to use the : operator and specify only the start and end points.

y = 5:8
y =
5 6 7 8
Notice that square brackets are not needed when you use the colon operator.
TASK
Create a row vector named x with the values 1, 2, 3, and 4, but this time using the : operator.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does x have four elements?
Does x have the correct values?
Does the script contain the colon operator?

The : operator uses a default spacing of 1, however you can specify your own spacing, as shown
below.

x = 20:2:26
x =
20 22 24 26
TASK
Create a row vector named x that starts at 1, ends at 5, and each element is separated by 0.5.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is x assigned correctly?

TASK
Create a row vector named x that starts at 3 and ends at 13, with each element separated by 2.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is x assigned correctly?

If you know the number of elements you want in a vector (instead of the spacing between each
element), you could instead use the 
linspace
 function:

linspace(first,last,number_of_elements)
.

Note the use of commas (,) to separate inputs to the linspace function.

x = linspace(0,1,5)
x =
0 0.250 0.500 0.750 1.000
TASK
Create a row vector named x that starts at 1, ends at 10, and contains 5 elements.

If you know the number of elements you want in a vector (instead of the spacing between each
element), you could instead use the 
linspace
 function:

linspace(first,last,number_of_elements)
.

Note the use of commas (,) to separate inputs to the linspace function.

x = linspace(0,1,5)
x =
0 0.250 0.500 0.750 1.000
TASK
Create a row vector named x that starts at 1, ends at 10, and contains 5 elements.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does x have five elements?
Does x have the correct values?

Answer :- x = linspace(1,10,5)

Both linspace and the : operator create row vectors. However, you can convert a row vector into a
column vector using the transpose operator (').

x = 1:3;
x = x'
x =
1
2
3
TASK
Transpose x from a row vector to a column vector using the transpose operator.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does x have five elements?
Is x a column vector?
Does x have the correct values?

You can create column vectors in a single command by creating the row vector and transposing it all
on one line. Note the use of parentheses here to specify the order of operations.

x = (1:2:5)'
x =
1
3
5
TASK
In a single command, create a column vector named x that starts at 5, ends at 9 and has elements
that are spaced by 2.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does x have three elements?
Is x a column vector?
Does x have the correct values?

Notice that if you are using linspace or : to create a vector, you don't need to use brackets ([]).

If you wanted to create an evenly-spaced vector from 


1
 to 

 with 100 elements, would you use linspace or :?
4.3 Array Creation Functions

MATLAB contains many functions that help you to create commonly used matrices, such as matrices of
random numbers.

x = rand(2)
x =
0.8147 0.1270
0.9058 0.9134

Note that the 2 in the command rand(2) specifies that the output will be a 2-by-2 matrix of random numbers.
TASK
Create a variable named x that is a 5-by-5 matrix of random numbers.

Many matrix creation functions allow you to input one number to create a square matrix (n-by-n) or
input two numbers to create nonsquare matrices.

x = rand(2)
x =
0.8147 0.1270
0.9058 0.9134

x = rand(2,3)
x =
0.6324 0.2785 0.9575
0.0975 0.5469 0.9649
TASK
Use rand to create an array that contains 5 rows and 1 column. Assign the result to a variable
named x.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does x have the correct size?
Does x have the correct values?

Most array creation functions accept the same inputs as rand. For example,
the zeros and ones functions create matrices of all zeros or ones, respectively.

x = ones(2,3)
x =
1 1 1
1 1 1
TASK
Use the zeros function to create a matrix of all zeros that has 6 rows and 3 columns (6-by-3). Assign
the result to a variable named x.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does x have the correct size?
Does x have the correct values?

How do you get the size of an existing matrix? You can use the size function.

size(x)

You can also create a matrix with the same size as an existing matrix in one line of code.

rand(size(x))
5.1 Indexing into Arrays

You can extract values from an array using row, column indexing.

y = A(5,7)

This syntax extracts the value in the 5th row and 7th column of A and assigns the result to the
variable y.
TASK
Create a variable x that contains the value in the 6th row and 3rd column of the variable data.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is x assigned correctly?

You can use the MATLAB keyword end as either a row or column index to reference the last element.

y = A(end,2)
TASK
Use the end keyword to obtain the value in the last row and 3 rd column of the variable data. Assign
this value to a variable named x.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is x assigned correctly?
Is the keyword end in the script?
Note that you can use arithmetic with the keyword end. For example:

y = A(end-1,end-2)
TASK
Create a scalar variable x that contains the value in the second to last (end-1) row and 3rd column
of data.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is x assigned correctly?

If you only use one index with a matrix, it will traverse down each column in order. Using one index,
try extracting the eighth element of data.

You can also use variables as your index. Try creating a variable y, and using y as the index to data.

DOUBT
5.2 Extracting Multiple Elements

When used as an index, the colon operator (:) specifies all the elements in that dimension. The
syntax

x = A(2,:)

creates a row vector containing all of the elements from the second row of A.
TASK
Create a variable named density that contains the second column of the matrix named data.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable density exist?
Is density assigned correctly?

The colon operator can refer to a range of values. The following syntax creates a matrix containing
the first, second, and third rows of the matrix A.

x = A(1:3,:)
TASK
Create a variable volumes containing the last two columns of data.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable volumes exist?
Is volumes assigned correctly?

A single index value can be used to reference vector elements. For example

x = v(3)
returns the third element of vector v when v is either a row or column vector.
TASK
Using a single index value, create a variable named p containing the 6th element in the
vector density.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable p exist?
Is p assigned correctly?

A single range of index values can be used to reference a subset of vector elements. For example

x = v(3:end)

returns a subset of vector v containing the elements from 3 to the end.


TASK
Using a range of index values, create a vector named p containing the 2nd through 5th elements
of density.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is p assigned correctly?

Example : [1 2;3 4;5 6; 7 8]

Ans : 1 2

3 4

5 6

7 8
5.3 Changing Values in Arrays

Remember you can use the : character to extract entire columns of data.


TASK
Create a vector named v2 containing the last column of data.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable v2 exist?
Is v2 assigned correctly?

Elements of a variable can be altered by combining indexing with assignment.


A(2) = 11
TASK
Change the first element in v2 from NaN to 0.5.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is v2 assigned correctly?
TASK
Change the value of the element in the first row and last column of data to 0.5.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is element (1,4) now 0.5?
Are the other elements unchanged?

You can combine indexing with assignment to change array values to equal other elements. For
example, this code would change the value of x(1) to x(2):

x(1) = x(2)

Try changing the first column of data to the second column of data.

Ans - data(1,:)=data(2,:)
6.1 Performing Array Operations on Vectors

MATLAB is designed to work naturally with arrays. For example, you can add a scalar value to all the
elements of an array.

x = [1 2 3];
y = x + 2
y =
3 4 5
TASK
Add 1 to each element of v1 and store the result in a variable named r.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable r exist?
Is r assigned correctly?

You can add together any two arrays of the same size.

z = x + y
TASK
Create a vector vs that is the sum of the vectors v1 and v2.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable vs exist?

Is vs assigned correctly?

You can multiply or divide all of the elements of an array by a scalar.

z = 2*x
y = x/3
TASK
Create a variable va that contains the value vs divided by 2 (the average volume).
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable va exist?
Is va assigned correctly?

Basic statistical functions in MATLAB can be applied to a vector to produce a single output. The
maximum value of a vector can be determined using the max function.

xMax = max(x)
TASK
Create a variable vm containing the maximum of the va vector.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable vm exist?
Is vm assigned correctly?
MATLAB has functions that perform mathematical operations on an entire vector or array of values in
a single command.

xSqrt = sqrt(x)
TASK
Using the round function, create a variable named vr which contains the rounded average
volumes, va.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable vr exist?
Is vr assigned correctly?

The * operator performs matrix multiplication. So, if you use * to multiply two equally sized vectors,
since the inner dimensions do not agree, you will get an error message.

z = [3 4] * [10 20]

Error using *
Incorrect dimensions for matrix multiplication.

In contrast, the .* operator performs elementwise multiplication and allows you to multiply the
corresponding elements of two equally sized arrays.

z = [3 4] .* [10 20]

z =
30 80
TASK
Create a variable named mass containing the elementwise product of density and va.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable mass exist?
Is mass assigned correctly?

You have performed array operations with


 two arrays of the same size
 a scalar and an array

There are other compatible sizes. For example, try the following:

x = [1 2;3 4;5 6; 7 8].*[1;2;3;4]

What size is x?

You can read more about this behavior here:


Compatible Array Sizes for Basic Operations

(https://in.mathworks.com/help/matlab/matlab_prog/compatible-array-sizes-for-basic-
operations.html)
7.1 Obtaining Multiple Outputs from Function Calls

The size function can be applied to an array to produce a single output variable containing the array
size.

s = size(x)
TASK
Create a variable named dsize containing the size of the data variable.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable dsize exist?
Is dsize assigned correctly?

The size function can be applied to a matrix to produce either a single output variable or two output
variables. Use square brackets ([ ]) to obtain more than one output.

[xrow,xcol] = size(x)
TASK
Create the variables dr and dc which respectively contain the number of rows and columns of the
variable data.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable dr exist?
Is dr assigned correctly?
Does the variable dc exist?
Is dc assigned correctly?

The maximum value of a vector and its corresponding index value can be determined using
the max function. The first output from the max function is the maximum value of the input vector.
When called with two outputs, the second output is the index value.

[xMax,idx] = max(x)
TASK
Create the variables vMax and ivMax containing the maximum value of the v2 vector and the
corresponding index value respectively.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable vMax exist?
Does the variable ivMax exist?
Is vMax assigned correctly?
Is ivMax assigned correctly?

Ans :

vMax =10.1570

ivMax= 5(index value (row))

If you only need the second output from a function, you can use a tilde ( ~) to ignore specific outputs.

For example, you might only want the index containing the maximum value in a vector:
density = data(:,2)
[~,ivMax] = max(v2)
densityMax = density(ivMax)

Try getting the index value of the minimum value in v2. Use this index to extract from density.
8.1 Obtaining Help: (1/2) Using MATLAB's Documentation

The MATLAB documentation contains examples and information that can help you when working on
your own problems.
TASK
Use the documentation for randi to help complete the task below.

Create a matrix named x that


 Contains random integers in the range from 1 to 20
 Has 5 rows
 Has 7 columns
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable x exist?
Is x assigned correctly?

Ans : x=randi(20,5,7)

You can also open the documentation using the doc function. Try opening the documentation
for randi with the code below:

doc randi

Search the documentation to create a 5-by-7 matrix with normally distributed numbers (instead of
uniformly distributed numbers).
9.1 Plotting Vectors

Two vectors of the same length can be plotted against each other using the plot function.

plot(x,y)
TASK
Create a plot with sample on the x-axis and mass1 on the y-axis.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is sample on the x-axis?
Is mass1 on the y-axis?

The plot function accepts an additional argument that allows you to specify the color, line style, and
marker style using different symbols in single quotes.

plot(x,y,"r--o")

The command above plots a red (r) dashed (--) line with a circle (o) as a marker. You can learn more
about the symbols available in the documentation for Line Specification.
TASK
Plot mass2 (y-axis) against sample (x-axis). Use red (r) star (*) markers and no line in your plot.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is sample on the x-axis?
Is mass2 on the y-axis?
Is the marker, line style, and color correct?

Notice that each plot command created a separate plot. To plot one line on top of another, use
the hold on command to hold the previous plot while you add another line.

plot(x1,y1)
hold on
plot(x2,y2)
TASK
Enter the hold on command.

Then plot mass1 (y-axis) against sample (x-axis) with black (k) square (s) markers and no line.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Was hold on entered?
Is sample on the x-axis?
Is mass1 on the y-axis?
Is the marker, line style, and color correct?

While the hold state is on, plots will continue to go on the same axes. To return to the default plot
behavior, where each plot gets its own axes, enter hold off.
TASK
Enter the hold off command.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Was hold off entered?

When you plot a single vector by itself, MATLAB uses the vector values as the y-axis data and sets
the x-axis data to range from 1 to n (the number of elements in the vector).
TASK
Plot the vector v1 using the command below.

plot(v1)

The plot function accepts optional additional inputs consisting of a property name and an associated
value.

plot(y,"LineWidth",5)

The command above plots a heavy line. You can learn more about available properties in the
documentation for Line Properties.
TASK
Plot v1 with a line width of 3.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is the x-axis correct?
Is v1 on the y-axis?
Is the line width correct?

You can provide additional inputs to the plot function after the line specifier.

plot(x,y,"ro-","LineWidth",5)
TASK
Plot v1 (y-axis) against sample (x-axis) with red (r) circle (o) markers and a solid line (-). Use a line
width of 4.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is sample on the x-axis?
Is v1 on the y-axis?
Is the marker and color correct?
Is the line width correct?

https://in.mathworks.com/products/matlab/plot-gallery.html

The plot function creates lines. There are many other plotting functions in MATLAB. You can see an
extensive list in the MATLAB Plot Gallery.

Each plot has different customization options. Try creating a histogram of density with
the histogram function. Set the "FaceColor" to yellow ("y").

.
9.2 Annotating Plots
Labels can be added to plots using plot annotation functions, such as title. The input to these
functions is a string. Strings in MATLAB are enclosed in double quotes ( ").

title("Plot Title")
TASK
Add the title "Sample Mass" to the existing plot.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is the plot title correct?

TASK
Use the ylabel function to add the label "Mass (g)".
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is the plot ylabel correct?

You can add a legend to your plot using the legend function.

legend("a","b","c")
TASK
Create a legend with the labels "Exp A" and "Exp B", in that order.
You can use a variable's value in plot annotations by concatenating a string with a variable:

bar(data(3,:))
title("Sample " + sample(3) + " Data")
10.1 Project - Electricity Usage

TASK
Electricity data is stored in a file named electricity.mat. Load that MAT-file into MATLAB.

Then enter usage in the script to see the matrix.


Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Do the variables prices and usage exist?
Is the command usage in the script?

Ans :
load electricity.mat
usage

In MATLAB, NaN (or, "Not a Number") is used to represent missing data.


TASK
One of the elements in the usage variable has a value of NaN. Replace this value with the value 2.74.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is the NaN replaced correctly?
Are the other elements unchanged?

Ans :

usage(2,3) = 2.74

The residential data is stored in the first column. Create a variable res that contains the first column of usage.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable res exist?
Is res assigned correctly?

Ans :

res = usage(:,1)
The commercial data and industrial data are stored in the second and third column, respectively.
Create variables comm and ind that contain the second and third columns of usage.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable comm exist?
Does the variable ind exist?
Is comm assigned correctly?
Is ind assigned correctly?

The usage data was collected annually between the years 1991 to 2013. The yrs variable you create
will help you to plot the data over a meaningful range.
TASK
Create a vector named yrs that represents the years starting at 1991 and ending with 2013.
Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Does the variable yrs exist?
Is yrs assigned correctly?

Ans

yrs=1991:2013

TASK

Create a plot with all three columns. Use yrs as the x-data. Use this order and these plot
specifications:

1. res: blue (b) dashed line (--)


2. comm: black (k) dotted line (:)
3. ind: magenta (m) dash-dot line (-.)
(Line specification options)

Hint
Submit
See Solution
Next task
Reset
Test Results:

Correct!
Is the first plot created correctly?

Is the second plot created correctly?

Is the third plot created correctly?

Ans :-
plot(yrs,res,"b--")
hold on
plot(yrs,comm,"k:")
plot(yrs,ind,"m-.")
hold off

Add the title "July Electricity Usage" to the existing plot.

Create a legend with the values "res", "comm", and "ind".


Hint
Submit
See Solution
Next task
Reset
Test Results:
Correct!
Is the title created correctly?
Is the legend created correctly?

When looking at the figure, it is clear that the industrial sector's electricity usage is fairly consistent
and does not seem to fluctuate as much as the residential and commercial sectors.
Audio Frequency
Audio signals are usually comprised of many different frequencies. For example, in music, the note
'middle C' has a fundamental frequency of 261.6 Hz, and most music consists of several notes (or
frequencies) being played at the same time.

In this project, you will analyze the frequency content of an organ playing the C chord.

The C chord consists of the C (261.6 Hz), E (329.6 Hz), and G (392.0 Hz) notes. The highlighted
points in this frequency plot correspond to each note.

You might also like