Categories

## Column Vector Matlab

MATLAB is a simple programming language owned and developed by MathWorks. It was started as a programming language for matrices as programming of linear algebra was simple. Matlab can be implemented as batch jobs and also as interactive sessions. In this article, we will understand a very basic and useful element of MATLAB called ‘Column Vector Matlab’.

## Uses of Column Vector Matlab:

• Computation
• Simulation
• Modeling
• Data analytics
• Prototyping
• Application development
• Engineering & Scientific graphics

Column vectors in MATLAB are created by keeping the required set of elements in a square bracket. A semicolon is then used for delimiting the elements. In simpler words, we can create a column vector using a square bracket [ ]. Elements in a column vector are then separated by either a newline or a semicolon (newline can be obtained by pressing the Enter key).

## Examples of Column Vector Matlab

Now let us understand this by a couple of examples:

## Code:

``a = [1; 3; 5]``

The output that we will get will be a single column with elements 1, 3, 5.

## Code:

``a = [1; 3; 5; 7; 9]``

The output that we will get will be a single column with elements 1, 3, 5, 7, 9

## Output:

The elements in a column vector may also be the result of arithmetic operations. Let us understand this by the following examples:

## Example 3 – Creating a Column Vector with Different Elements

Let us try to create ‘y’, a column vector with elements having the following description:

• 20 inches converted to cm (1 inch is 2.54 cm).
• 140 degrees Fahrenheit converted to Centigrade (conversion formula is Centigrade = 5 (F – 32) / 9).
• 120 lbs in kgs (one kg = 2.2 lbs).

## Code:

``y = [20 / 2.54; (5 / 9) * (140 - 32); 120 / 2.2]``

The output that we will get will be a single column with 3 elements.

## Example 4 – Creating a Column Vector with Arithmetic Operations

Let’s take a simpler example which involves simple arithmetic operations:

## Code:

``y = [20 + 2; 59 - 9; 120 / 2]``

The output that we will get will be a single column with 3 elements.

## Operations Between Row and Column Vector in Matlab

One thing to remember here is that we access elements of a column vector using normal round brackets ( ) which is exactly how we access elements of row vectors. Vector arithmetic is also the same for column vectors and for row vectors. The restriction to be kept in mind is that we cannot mix column and row vectors.

Convert Vectors using Transpose: We can convert our column vector into a row vector by using TRANSPOSE. Creating a row vector from a column vector using Transpose.

## Code:

``a = [1; 3; 5]’``

## Output:

The output that we will get will be a single row with elements 1, 3, 5. As we can observe, instead of getting a column vector here, we have received a row vector. This is because we have used a ‘Transpose’ in the MATLAB command.

Categories

## Matlab ezplots

MATLAB is also a great tool for visualization. It provides us with ability to create a wide variety of plots. In this article, we will focus on ezplot function for creating plots of functions and equations.

## Syntax:

Let us understand the Syntax of ezplot function in MATLAB

1. `ezplot (f)`
2. `ezplot (f, [minimum, maximum])`
3. `ezplot (x, y)`

## Description of ezplot function in Matlab

1. ezplot (f):
1. ezplot (f) will create a plot of an equation, symbolic expression or a function passed as an argument
2. Ezplot (f) by default will plot a function or an expression over [–2π to2π] or a subinterval of [–2π to 2π]
2. ezplot (f, [minimum, maximum]):
1. This function will plot the input function or equation over the range passed in the argument
3. ezplot (x, y):
1. This function will plot the planar defined curves xand y over 0 <= z <= 2π or over a subset of 0 <= z <= 2π

## Examples:

Let us understand ezplot (f) with a couple of examples:

## Example 1:

Let us take a simple example of sine function and try to plot it using ezplot.

``syms x[initializing variable x] ezplot(sin(x))[passing the input function]``

[Here notice that we have not passed any argument for the interval, so by default, ezplot function will plot the sine wave in the interval [–2π to 2π] ]

## Input:

``````syms x
ezplot(sin(x))``````

## Output:

As we can see in our output, the sin function is plotted between the range [–2π to 2π] ].

Next, we will pass an argument to define the interval for our output.

## Example 2:

Let us take a cos function and try to plot it using ezplot in the range 0 to 2π

``syms x[initializing variable x] ezplot(cos(x), [0, 2 * pi])[passing the input function and the required interval][Here notice that we have passed [0 to 2π] as an argument for the interval]``

## Input:

``````syms x
ezplot(cos(x), [0, 2 * pi])``````

## Output:

As we can see in our output, the cos function obtained is in the range 0 to 2 pi; as expected by us.

## Example 3:

In this example, we will use ezplot (x, y) to create plot of a straight line equation

``syms x y[initializing variables x& y] ezplot(x == 5 * y )[passing the input straight line equation]``

[Notice the double equal to sign for representing ‘=’ ]

## Input:

``````syms x y
ezplot(x == 5 * y )``````

## Output:

As we can see, we have obtained a graph for equation of a straight line.

## Example 4:

In this example, we will plot equation for a sphere using ezplot (x, y).

``syms x y[initializing variables x& y] ezplot(x ^ 2 + y ^ 2 == 25 )[passing the equation of a sphere with radius 5]``

[Notice the double ‘equal to’ sign for representing ‘=’ ]

## Input:

``````syms x y
ezplot(x ^ 2 + y ^ 2 == 25 )``````

## Output:

As we can see in our output, we have obtained a sphere of radius 5 sing ezplot function.

Categories

## Plot legend

MATLAB provides us with plenty of functionalities, useful in various computational problems. As we have learned in our previous articles, we can create vector plots in MATLAB using the ‘plot’ function. In this article, we will learn how to put Legends to the plots created in MATLAB. First, let us understand why we need to have legends for our plots. We create plots for visualizing our data and as we learned already, a single plot can have more than 1 vector or function in it. In such cases, we must provide more info about the functions drawn in the plot Legends are the way to provided information about different functions contained in a single plot

## Syntax:

The syntax for creating Legends in MATLAB:

`legendlegend(L1, L2, ...., L N) , where L1, L2 and so on represents the respective labels.`

Explanation: This function will create a legend for each data series used in the plot, with descriptive labels. The function ‘legend’ will create labels like ‘data1’, ‘data2’, and so on.

## Examples to Implement Matlab Plot Legend

Let us understand the function with an example:

## Example 1:

First, we will define ‘A’ as a vector containing values between 2pi (π) and 3π. We will define an increment of π/50 between these values.

Next, we will define B as the cos function of values of A and C as sine function of values of A

A = 2*pi : pi/50 : 3*pi

B = cos (A)

C = sin (A)

Now to understand how ‘Legend’ works, we will first plot our input functions and then use the function ‘legend’.

Our inputs A, B& C are first passed as arguments to the function ‘plot’.

And then we simply write ‘legend’ in our code to get the labels.

This is how our input and output will look like in MATLAB console:

## Code:

``````A = 2*pi : pi/50 : 3*pi
B = cos (A)
C = sin (A)
figure
plot(A,B,A,C)
legend``````

## Output:

Explanation: As we can see in the above output, we have plotted 2 vectors and our legend function created corresponding labels. Since nothing was passed as an argument to legend function, MATLAB created labels as ‘data1’ and ‘data2’.

## Example 2:

Now, what if instead of ‘data1’ and ‘data2’, we want to have the name of the function as the label.

Let us learn how to do it.

Our initial code will be the same as in the above example

A = pi : pi/100 : 3*pi

b = cos (A)

c = sin (A)

In addition to the above code, we will add the below-mentioned line:

``legend({'sin(A)', 'cos(A)'})``

As we can see, we have passed the name of the functions as an argument to our legend function. Here, we can name our functions as per our needs.

This is how our input and output will look like in MATLAB console:

## Code:

``````A = pi : pi/100 : 3*pi
b = cos (A)
c = sin (A)
figure
plot (A, b, A, c)
legend({'sin(A)','cos(A)'})``````

## Output:

Explanation: Notice on the top right side of the plot, we have got the names of our functions.

## Example 3:

Next, what if we don’t want our labels to be on the top right but in some other place on the plot.

Let us learn how to achieve that.

Legend function in MATLAB allows us to put our label in place of our choice. All we need to do is pass the pre-defined code for the direction, as an argument.

Our initial code will not change:

A = pi : pi/100 : 3*pi

b = cos (A)

c = sin (A)

In addition to the above code, we will add the below-mentioned line:

``legend ({'sin(A)', 'cos(A)'}, 'Location','northwest')``

Notice that in addition to the names of the functions, we have added 2 more arguments:

‘Location’ & ‘northwest’. Here ‘Location’ is a keyword for setting the direction of our labels and ‘northwest’ is pre-defined code for direction (Please refer to Table the end of the article to get pre-defined direction codes).

This is how our input and output will look like in MATLAB console:

## Code:

``````A = pi : pi/100 : 3*pi
b = cos (A)
c = sin (A)
figure
plot (A, b, A, c)
legend({'sin(A)','cos(A)'},'Location','northwest')``````

## Output:

Explanation: As we can clearly see in our output, the label is now on the top left (north west direction).

## Example 4:

Next, we will learn how to give a name to our label box. i.e we want to convey that sin(A) and cos(A) are our ‘FUNCTIONS’.

Here also our initial code will be the same as above. In addition to that, here we will add the following code:

`title(legend,'FUNCTIONS’)`

This is how our input and output will look like in MATLAB console:

## Code:

``````A = 2*pi : pi/500 : 3*pi
b = cos (A)
c = sin (A)
figure
plot (A, b, A, c)
legend({'sin(A)','cos(A)'},'Location','northwest')
title(lgd, 'Functions')``````

## Output:

Explanation: As we can notice in the output, our label box is now named.

Categories

## Matlab Legend

Graphs are the graphical form of the explained data in the data set. Legends are the way of adding them to the graph to explain the displayed data that have different properties and forms. They are mainly used in graphs, charts or spreadsheets. For each legend, there is a legend key that is linked to every data displayed in the chart. Legends can be used in various graphs or charts like a bar graph, line graph, pie chart, etc. It should be always noted that the parameters that we define in the legend command should be equal to the number of attributes in the plot command.

## Working of Matlab Legend

In Matlab, legends are used to label the plotted data for every parameter that is mentioned. For labels, it uses one of the properties of data series which is known as DisplayName. The legend updates automatically whenever we include any new or remove data series from the current axes. If there are no current axes present, then there is no legend and it is empty.

## Syntaxes that are used in Matlab:

• L=legend: This is used to include the legend in the plotted data series.
• L=legend (label of the legend 1…label of the legend N): This includes the legend labels in the graph as specified in the labels argument. We can mention the label in the form of strings or characters. For example, legend (‘Mon’,’Tue’,’Wed’)
• L=legend (labels of the legend): This is used to mention the labels in the legend. Labels can be a string array, character vectors or a character matrix.
• L=legend (subset included): This includes only the values that are present in the subset. We can specify the subset as the values or no arguments in the input.
• L=legend (target axes, ___): This is used to specify the required axes or chart in the target axes argument.
• L=legend (__,’location of the legend’): This is used to specify the location of the legend that should be placed in the plot. This property of the legend should always be given after all the input arguments.
• L=legend (__,’orientation of the legend’): This is used to specify the orientation of the legend that should be placed in the plot. The default value of the orientation is vertical.
• L=legend (___,’Name of the property’, ‘value of the property’): This is used when we want to customize the appearance of legends in the plot. We can give the property name in ‘Name of the property’ argument and the required value after that. There are various properties of the legends which are discussed below.
• L=legend(bkgd): This is used to set the background appearance and its outline. The default value of it is ‘boxon’.
• L=legend(visibility): This is used to set the visibility of the legend which has different values like the show, hide and toggle.
• L=legend(off): This is used to delete the legend and its customization from the plot.

## Examples of Matlab Legend

Please find the below examples that explain the use of legends in Matlab:

## Example 1:

To plot two lines and display the legend in the present chart.

## Code:

``````a = linspace(0,2*pi);
y = sin(a);
plot(a,y)
hold on
y1 = sin(2*a);
plot(a,y1)
legend('sin(a)','sin(2*a)')``````

## Output:

In the above example, the legend for the two lines is shown in the top right corner of the plot, one line depicting the values for the function sin(a) and the other line depicting the values for the function sin(2a).

## Example 2:

To plot another line and specify the labels of the legend using DisplayName property of the legend in the plot command. In this example, we have added another line to the existing line as mentioned in the above example.

## Code:

``````a = linspace(0,2*pi);
y = sin(a);
plot(a,y)
hold on
y1 = sin(2*a);
plot(a,y1)
legend('sin(a)','sin(2*a)')
y2 = sin(3*a);
plot(a,y2,'DisplayName','sin(3a)')
hold off``````

## Output:

In the above example, another line is added to an existing plot using the legend label in the plot command as shown in the highlighted part. This can be done by using the legend property ‘DisplayName’ and the label of the legend as its value. Here sin(3a) is the value and it is added as legend label to the plot.

There are various properties of the legend in Matlab which are discussed below. Location is one of the main property of the legend which decides the location of the legend.

There are various values that can be assigned to the property like:

• north: This is used to plot the legend in top of the axes or chart and is placed inside of the chart.
• northeast: This is used to plot the legend in the top right of the axes or chart.
• northwest: This is used to plot the legend in the top left of the axes or chart.
• northoutside: This is used to plot the legend on top of the axes and it is outside.
• south: This is used to plot the legend at the bottom of the axes or chart and is placed inside of the chart.
• southeast: This is used to plot the legend in the bottom right of the axes or chart.
• southwest: This is used to plot the legend in the bottom left of the axes or chart.
• southoutside: This is used to plot the legend at the bottom of the axes and it is outside.
• east: This is used to plot the legend in the right of the axes or chart and is placed inside of the chart.
• eastoutside: This is used to plot the legend in the right of the axes and it is outside.
• west: This is used to plot the legend in the left of the axes or chart and is placed inside of the chart.
• westoutside: This is used to plot the legend in the left of the axes and it is outside.
• There are many other locations apart from this which are also used in Matlab.
• We can also decide the visibility, orientation of the legend which can be horizontal and vertical depending on the requirements.

## Example 3:

To delete the legend from the plot.

## Code:

``````a = linspace(0,2*pi);
y = sin(a);
plot(a,y)
legend('sin(a)')``````

## Code:

``````a = linspace(0,2*pi);
y = sin(a);
plot(a,y)
legend(‘off’)``````

Categories

## Plot Vector Matlab

MATLAB provides us with plenty of functionalities, useful in various computational problems. In this article we will learn how to create vector plots in MATLAB. First let us understand why we need to plot the vectors. We create plots for visualizing our data Data visualization is useful in getting a high-level understanding of the data Data plots to have a wide range of uses; comparing a large amount of data, tracking changes in data over time

## Syntax:

``Plot (A, B)``

Explanation: This function will plot vectors A & B, with the condition that both A & B should be of the same length Simply put, a plot will be created between data points in A versus B.

## Examples to Implement Plot Vector Matlab

Here are the examples:

## Example 1:

First, we will define ‘A’ as a vector containing values between pi (π) and 3π. We will define an increment of π/100 between these values. Next, we will define B as the cos function of values of A. Our inputs A & B are then passed as arguments to the function plot (A, B). This is how our input and output will look like in MATLAB console:

## Code:

``````A = pi : pi/100 : 3*pi;
B = cos (A);
figure
plot(A,B)``````

## Example 2:

Let us understand this with the help of ‘A’ that we used in the above example. Additionally, we will define ‘b’ and ‘c’ as 2 more vectors with sine & cos values of A respectively. Our inputs A, b & c are then passed as arguments to our function. This is how our input and output will look like in MATLAB console:

## Code:

``````A = pi : pi/100 : 3*pi
b = sin (A);
c = cos (A);
figure
plot(A,b,A,c)``````

## Example 3:

Next, what if we need to visualize these 2 plots obtained side by side in some other style. That is, is there a way to define the style of plots? Yes, there is, we simply need to pass the pre-defined line style in the argument of our plot function. (Please refer to Table 1 at the end of the article for pre-defined line styles) As an example, let us plot the above input as a dashed line and a dotted line. We will plot our sine function as a dashed line and cos function as a dotted line. Our inputs A, b & c are then passed as arguments to our function. This is how our input and output will look like in MATLAB console:

## Code:

``````A = pi : pi/100 : 3*pi
b = sin (A)
c = cos (A)
figure
plot(A,b,’--’,A,c,’:’)``````

As we can notice in our input, we have passed the pre-defined line style for ‘b’ and ‘c’ to get dashed and dotted plots respectively.

## Example 4:

Next we will learn how to get plots with the color of our choice. For this also, we pass the pre-defined color code as an argument to our pot function. As an example, we will try to obtain the above plot in yellow and magenta color. Let’s have a sine function in yellow color and cosine function in magenta. (Please refer to Table 2 at the end of the article to get pre-defined color codes) This is how our input and output will look like in MATLAB console:

## Code:

``````A = pi : pi/100 : 3*pi
b = sin (A)
c = cos (A)
figure
plot(A,b,'y',A,c,'m')``````

As we can see in our input, all we did is passed the desired color code in the argument.

## Output:

As we can see in the output obtained, sine and cosine functions are obtained in yellow & magenta color respectively, as expected.

Categories

## Histogram in Matlab

Histogram is a representation of any statistical information showing the frequency of data items in successive intervals. MATLAB supports plotting histogram feature that enables the user to create a bar graph for any vector or matrix and grouping the data into bins using an automatic binning algorithm. For each bin, the area represents the frequency of occurrence of the data, not the height. It supports customization in histogram presentation.

## Syntax:

In earlier versions, hist() and histc() were used to generate histogram plots. In later versions those functions are replaced with new functions with advanced capabilities i.e. histogram(), histcounts() and discretize().

The syntax for the above-recommended functions are as follows:

• histogram(X, a1,a2,…..,an)
• histcounts(X, a1,a2,…..,an)
• discretize(X, a1,a2,…..,an)

Where X: Data input in the form of vector or matrix.

a1,a2,…..,an: Attribute values (optional)

Creation of Histogram in Matlab: MATLAB makes it a single click action to create a histogram for any data. A histogram can be created by using the inbuilt function histogram().

## Example:

The below code is written to generate 100 random numbers and histogram() is used to plot a histogram for the generated data.

## Code:

``````data = randn(100,1);
h = histogram(data)``````

## Output:

Once any histogram object is created, it can be altered by altering its property values, that makes changes in the properties of bins and thus in the display.

## Properties of Histogram in Matlab

Various properties that are featured for the histogram in MATLAB, are as follows:

## 2. Categories

This property allows to plot histogram for each category defined in the input categorical array. If bin count is specified, categories sets the associated category descriptions in the plot.

This property contains parameters such as mentioned below:

## 3. Data

This value gets distributed over a histogram plot among the bins. This property consists of different parameters such as:

## 5. Legend

This property in the MATLAB adds descriptive labels to the plots. It comprises of:

Categories

## Linspace MATLAB

MATLAB is a technical computing language. MATLAB gets its popularity from providing an easy environment for performing and integrating computing tasks, visualizing & programming.

Uses of MATLAB include (but not limited to)

• Computation
• Simulation
• Modeling
• Data analytics (Analysing and Visualizing data)
• Prototyping
• Application development
• Engineering & Scientific graphics

## Linspace Function in MATLAB

In this article, we will understand a very useful function of MATLAB called ‘linspace’. This function will generate a vector of values linearly spaced between two endpoints. It will need two inputs for the endpoints and an optional input to specify the number of points to include in the two endpoints.

### Syntax of linspace function:

``X = linspace(a1, a2)``

Now let us understand this one by one

## 1. X=linspace(a1,a2)

This function will return a row of a vector of 100(default) linearly spaced points between a1 and a2

• a1 and a2 can be real or complex
• a2 can be either larger or smaller than a1
• If a2 is smaller than a1 then the vector contains descending values

Here is an example to understand this:

## Example 1:

``X = linspace(-1, 1)``

It will generate a vector of 100 evenly spaced vectors for the interval [-1, 1]

## Example 2:

``X = linspace(2, 3)``

It will generate a vector of 100 evenly spaced vectors for the interval [2,3]

## Example 3:

``X = linspace(2, 1)``

Here a2 is smaller than a1, it will generate a vector of 100 evenly spaced vectors for the interval [2,1] in descending order

## 2. X=linspace(a1,a2,n)

This function will return a row of a vector of “n” points as specified in input for linearly spaced points between a1 and a2. This function gives control of the number of points and will always include the endpoints specified in the input as well.

The spacing between the points is (a2-a1)/(n-1).

• If n is 1, the function will return a2 as output
• If n is zero or negative, the function will return 1by0 empty matrix

Here is an example to understand this:

## Example 1

``X = linspace(-1, 1, 7 )``

It will generate a vector of 7 evenly spaced vectors for the interval [-1, 1]

## Example #2

``X = linspace(2,3,5)``

It will generate a vector of 5 evenly spaced vectors for the interval [2,3]

## Example 3:

``X = linspace(2, 3, 1)``

Here n = 1, so the function will return a2 input parameter

## Example 4:

``X = linspace (5, 1, 0)``

Here n = 0, so function will return 1X0 empty double row vector

Output:

## Vector of evenly spaced Complex numbers

``X = linspace(2+2i, 3+3i)``

Here a1 and a2 are complex numbers, it will generate a vector of complex numbers for 100 evenly spaced points for the interval [2+21, 3+3i]

## Output:

``X= linspace(1+1i, 5+5i, 4)``

It will generate a vector of complex numbers with 4 evenly spaced point for the interval [1+1i, 5+5i]

## Output:

The linspace function in MATLAB provides us with an array/matrix comprising the desired number of values starting from and ending at a declared value. The produced array will have exactly the desired number of terms which will be evenly spaced. The values will be in the range of start and end values passed. So, the linspace function will help us in creating an instantiated matrix or array.

Categories

## Plot Multiple Lines

A line drawn with Matlab is feasible by incorporating a 2-D plot function plot() that creates two dimensional graph for the dependent variable with respect to the depending variable. Matlab supports plotting multiple lines on single 2D plane. The lines drawn from plot function can be continuous or discrete by nature. The lines for data Y1, Y2,…,Yn with respect to their corresponding set of data X1, X2,.., Xn. Matlab can generate multiple 2D line plots using the plot function within a loop. The customization of the plots is also feasible by altering different attributes of plot function.

## Syntax:

The general syntax to plot multiple lines within a single plan is:

``plot(X1,Y1,...,Xn,Yn)``

Whereas depending on the attributes used in order to customize the display of the lines, the syntax is defined as:

``plot(X1,Y1,LineSpec1,...,Xn,Yn,LineSpecn)``

This syntax sets the line style, marker type, and color for each line. LineSpeci get applied to the data pair Xi,Yi.

``plot(___,Name,Value)``

This syntax is used to apply customization to the display of the lines using name value pair arguments.

## Examples of Matlab Plot Multiple Lines

Given below are the examples mentioned:

## Example 1:

Let’s create 2 line plots for 2 functions y1=sin(x1) and y2=sin(2*x2) where x1 ranges from 0 to 3*pi x2 ranges from pi/2 to 3*pi.

## Code:

``````x1=0:pi/100:3*pi;
x2=pi/2:pi/100:3*pi;
y1=sin(x1);
y2=sin(2*x2);
figure
plot(x1,y1,x2,y2)``````

## Output:

The resultant plot consists of 2 sinusoidal line curves ‘y1’ and ‘y2’ having 2 different set of values ‘x1’ and ‘x2’, but share a common x-y plane.

The customization of the lines drawn from single plot functions can be achieved by altering any of the attribute or any combination of the attributes described below:

a. xlabel: Add labels to x-axis.

b. Ylabel: Add labels to y-axis.

c. Title: Update title for the graph.

d. Grid on: Makes the grid lines visible for the graph.

e. Axis equal: The plots can be created with a common scale factor and spaces for both the axis.

f. Axis square: Set of square plots can be generated.

The example defined below demonstrates the process of customization of the presentation of the graph by modifying the attributes given above.

## Code:

``````x=0:pi/100:2*pi;
y1=sin(x);
y2=cos(2*x);
%Adding x-label, y-label and title to the resultant plot
plot(x, y1,x,y2), xlabel('x-axis'), ylabel('y-axis'), title('Graph customisation'),``````

## Output:

g. Axis scaling

The limit values for the plots can be imposed on the axes using the command ‘axis’.

## Syntax to incorporates axes limit:

`axis ( [xminxmaxyminymax] )`

## Example:

``````x = [0 : 0.1: 20];
y1 = exp(-x).*cos(2*x);
y2= exp(-x).*sin(x);``````

## Case 1:

%x-axis maximum value 15

%x-axis minimum value 0

%y-axis minimum value -1

%x-axis maximum value 1

## Code:

``plot(x, y1,x,y2), axis([0 15 -1 1])``

## Case 2:

%The minimum value of y-axis gets updated to -0.1 and maximum value for x-axis gets updated to 12.

## Code:

``plot(x, y1,x,y2), axis([0 12 -0.1 1])``

## Output:

h. Arranging multiple line plots in different subplot: Matlab supports to present the line plots generated in single execution, with distinct set of axes.

The below example present 2 line plots generated from one singe execution of the program with two different set of axes.

## Code:

``````x1=[21 23 34 50];
y1=[29 41 23 21];
x2=[11 21 32 51 ];
y2= [ 21 31 52 61];
%Placing the first line plot in the first cell of the frame
subplot(1,2,1)
plot(x1,y1)
hold on
%Placing the second line plot in the second cell of the frame
subplot(1,2,2)
plot(x2,y2)
hold off``````

## Output:

i. Including legend to distinguish the line plots: Application of the attribute ‘legend’ adds information to the plot to guide the user in identifying the lines with respect to their plotting functions.

The code is written to display the data mapping each line to its corresponding plotting function.

## Code:

``````x = [0 :pi/100:2*pi];
y1 = sin(2*x);
y2 = cos(2*x+pi);
plot(x, y1, x, y2, '.-'), legend('Sin(2x)', 'Cos(2x+pi)')``````

## Example 2:

Generating multiple lines using loop.

Matlab enables user to plot more than two number of lines in single plane. This can also be achieved by calling the plot function in a loop where the plotting function can be defined as function of the looping variable.

The below code snippet generates 6 lines for the function defined by ‘y’ which is function of the looping variable ‘x’.

## Code:

``````t = [25 50 75 100 125 150] for i=1:length(t);
x=[20 23 45 56 30 12];
y= x*i+5;
figure(1)
hold on
plot(x,y,'LineWidth',2)
end``````

## Example 3:

Displaying markers for specific data points for the lines.

Markers helps to point out distinct data points on the plotted line to figure out the exact values calculated from the function. In case of graph containing lines more than 3 and having overlapped presentation, it helps to determine which data point belongs to which plot.

The below example generate 2 line plots and one plot is highlighted with marker symbol ‘-o’.

## Code:

``````x = linspace(0,10);
y1 = 2*x+5;
y2=4*x+6;
plot(x,y1,x,y2,'-o','MarkerIndices',1:1:50)``````

## Example 4:

Customizing the presentation of the lines after creation of the plot.

Matlab extends its feature in 2D line plot to customize the plot presentation through the execution even after the plot is generated. The generated plot gets assigned to a chart line object and its display gets customized by altering the attributes from the storing chart line object.

The below code is written to generate two linear curves and edit the display of the graphs by altering the attributes of the chart line object.

Phase 1: Creation of the plots.

## Code:

``````x = linspace(-2*pi,2*pi);
y1 = 2*x+5;
y2=4*x+6;
p = plot(x,y1,x,y2);``````

## Output:

Phase 2: Editing the display of the plot using attributes from the chart line object ‘p’.

## Code:

``````p(1).LineWidth = 2;
p(2).Marker = '*';``````

## Output:

Note: Input values like ‘NaN’ and ‘Inf’ breaks the line plots. Colors and line styles are applied based on the ColorOrder and LineStyleOrder properties of the axes for any line plot.

Categories

## Matlab Plot Circle

MATLAB can be used to perform operations involving geometric figures like circles, rectangles, squares etc. In this article, we will focus on circles. We will learn how to create various types of circles in MATLAB. We can create solid or plane circles in MATLAB, which we will learn as we go ahead in the article. We will also learn how to create a circle using the rectangle function.

## How to Create a circle using Rectangle Function?

Let us first learn syntax to draw a simple circle in MATLAB:

1. Let us first declare some points, here we are taking 500 points. The below code will create these points.

• angles = linspace(0, 2*pi, 500);

2. Let us now declare the radius and centre of the circle. The centre will be defined by x and y co-ordinates.

• CenterX = 50;
• CenterY = 40;

3. Finally, we will plot our circle.

• x = radius * cos(angles) + CenterX;
• y = radius * sin(angles) + CenterY;

4. We will also write some code for our output to look visually better. This is normal formatting and we can adjust it as per our requirement.

• plot(x, y, ‘b-‘, ‘LineWidth’, 2);
• hold on;
• plot(CenterX, CenterY, ‘k+’, ‘LineWidth’, 3, ‘MarkerSize’, 14);
• grid on;
• axis equal;
• xlabel(‘X’, ‘FontSize’, 14);
• ylabel(‘Y’, ‘FontSize’, 14);

5. This is how our input and output will look like in MATLAB console:

## Code:

``````angles = linspace(0, 2*pi, 500);
CenterX = 50;
CenterY = 40;
x = radius * cos(angles) + CenterX;
y = radius * sin(angles) + CenterY;
plot(x, y, 'b-', 'LineWidth', 2);
hold on;
plot(CenterX, CenterY, 'k+', 'LineWidth', 3, 'MarkerSize', 14);
grid on;
axis equal;
xlabel('X', 'FontSize', 14);
ylabel('Y', 'FontSize', 14);``````

## Output:

As we can see in the above output, the circle is created with a radius 20 and centre (50, 40) as defined by us in the code.

## How to Create a Solid 2D Circle in MATLAB?

Next, let us learn how to create a solid 2D circle in MATLAB:

1. First, we will be creating logical image of circle. For this, we will define center, diameter and the image size. Let us first create image.

• imageSizeOfX = 640;
• imageSizeOfY = 480;
• [colInImage rowsInImage] = meshgrid(1 : imageSizeOfX, 1 : imageSizeOfY);

2. Next, we will be creating the circle inside the image.

• centerOfX = 320;
• centerOfY = 240;
• Pixels = (rowsInImage – centerOfY).^2 …
• + (colInImage – centerOfX).^2 <= radius.^2;

3. In the above line of code, Pixels is “logical” array and is 2D. Let us now display ‘Pixels’.

• image(Pixels);
• colormap([0 0 0; 1 1 1]);
• title(‘Image of circle’);

4. This is how our input and output will look like in MATLAB console:

## Code:

``````imageSizeOfX = 640;
imageSizeOfY = 480;
[colInImage rowsInImage] = meshgrid(1 : imageSizeOfX, 1 : imageSizeOfY);
centerOfX = 320;
centerOfY = 240;
Pixels = (rowsInImage - centerOfY).^2 ...
+ (colInImage - centerOfX).^2 <= radius.^2;
image(Pixels);
colormap([0 0 0; 1 1 1]);
title('Image of circle');``````

## How to create a Circle in MATLAB Using Rectangle Function?

Let us now learn how to create a circle in MATLAB using rectangle function: Here is a simple code to achieve this:

1. Like we discussed in above examples, we will declare the radius and centre co-ordinates of the required circle.

• centerX = 30;
• centerY = 40;
• ‘Curvature’,[1,1],…
• ‘FaceColor’,’b’);
• axis square;

2. We have passed ‘FaceColor’ as “b” so our output circle will be of Blue colour.

## Code:

``````radius = 6;
centerX = 30;
centerY = 40;
'Curvature',[1,1],...
'FaceColor','b');
axis square;``````

## How we can Create a Simple arc in MATLAB?

Finally, let us discuss how we can create a simple arc in MATLAB. As we know that arc is nothing but a small portion of the circle, code for creating an arc is also very similar to that of creating a circle.

1. First we define the parameters of required arc.

• xCenter = 1;
• yCenter = 1;

2. Next, we define the angle theta as required.

• theta = linspace(20, 100, 50);
• x = radius * cosd(theta) + xCenter;
• y = radius * sind(theta) + yCenter;

3. Finally, we plot our defined points.

• plot(x, y, ‘b-‘, ‘LineWidth’, 2);
• axis equal;
• grid on;

## Code:

``````xCenter = 1;
yCenter = 1;
theta = linspace(20, 100, 50);
x = radius * cosd(theta) + xCenter;
y = radius * sind(theta) + yCenter;
plot(x, y, 'b-', 'LineWidth', 2);
axis equal;
grid on;``````

Categories

## Surface Plot in Matlab

Plots are the means to show the distribution of the data graphically. If the plots are plotted properly then it shows a lot of relevant information to the uninformed audience about the significance of the plot. Sometimes, if the numbers are huge, then it is impossible to show it in the graph or plot. There are plots for the above scenario which are known as Surface plots and are used in visualizing the matrices if the range is too large to display it in the normal plot. In this topic, we are going to learn about Surface Plot in Matlab.

## Working of Surface Plot in Matlab with Syntax

In Matlab, surface plots can be done with the help of keyword “surf” with different arguments that serve various properties in the plot. There are different surface plots that can be created using Matlab.

Please find the below syntax with arguments used for plotting the surface plot:

• surf (e, f, g): This is used to create a three-dimensional plot where that can have different colors and properties. The values in matrix g can be implemented to plot the heights which is top of the grid as mentioned in e and f plotted in e-f plane. There are different colors for different values of g and it will be plotted as part of the surface plot.
• surf (e, f, g, C): This will plot the surface plot as described in the above syntax. C in the input argument is used to specify the color of the surface plot.
• surf(g): This is used to plot the surface plot with the values mentioned in the rows and columns of the matrix as given in g.
• surf (g, C): This will plot the surface plot as described in the above syntax. C in the input argument is used to specify the color of the surface plot.
• surf (axes value, __): This syntax is used to implement the surface plot with the given axes value instead of the current axes value and it should be mentioned as the first input argument.
• surf (___, Name of the command, the value of it): This syntax is used to plot the surface plot with respect to the property that we can mention in the command section and provide the value as required.

## Examples

Here are the following examples mention below

## Example 1:

``````[a, b] =meshgrid(1:0.5:10,1:20);
C = cos(a) + sin(b);
surf(a,b,C)``````

## Output:

There are several properties related to the surface plot which can change the look and feel of the surface plots.

Please find the list of properties which are used in Matlab:

• We can change the face color of each face depending on the values we give to the CData property of the surface plot. The values can be flat, RGB triplet value, texture map, interp, etc.RGB triplet values are unique for all the colors which provide the intensity levels of colors Red, Green, and Blue. The intensity level of the RGB triplet is in the range of [0,1]. The colors can be Red, Blue, Green, magenta, cyan, black, yellow, white and they have unique RGB values.
• We can also change the Face Alpha value of each surface. The values can be a scalar, flat, interp, texturemap. If the input is scalar then it ranges from 0 to 1, 0 being completely opaque and 1 is fully transparent. The values between 0 and 1 can be semitransparent. 1 is the default value for face alpha.

## Example 2:

``````[a, b] =meshgrid(1:0.5:10,1:20);
C = cos(a) + sin(b);
surf(a,b,C,'FaceAlpha',0.5)``````

## Example 3:

``````[a, b] =meshgrid(1:0.5:10,1:20);
C = cos(a) + sin(b);
surf(a,b,C,'FaceAlpha',0.4)``````

## Output:

• We can also modify the lighting of each face on the surface. The values that we can provide to the input argument are flat, Gouraud and none. If the value is flat, then the light is applied to each face uniformly and if the value is Gouraud then the light is changed across each face of the surface and if it none then no light is applied.
• We can also change the alignment to sharpen the vertical and horizontal edges of the plot. The values for this property can be OFF or ON. If the input of this property is OFF, then the edges of the plot will not be sharpened which will provide an uneven finish while if it is ON, then the horizontal and vertical edges will be sharpened to provide a smooth finish to the plot.
• We can also change the lighting of the horizontal and vertical edges. The values that we can provide to the input argument are flat, Gouraud and none. If the value is flat, then the light is applied to each face uniformly and if the value is Gouraud then the light is changed across each face of the surface and if it none then no light is applied.
• There are various properties that are related to marker, coordinate date, normal, lighting methods, legend, interactivity, callbacks, and identifiers. All the properties have their own functions and they can be used to change various properties of surface plots.