Categories
1. Basics of Matlab

Matlab randn

In Matlab ‘randn’ function is used for normal distribution; it gives random values as output. This function works according to arguments which are passed through function definition. We can pass single or multiple values as arguments in randn function. If arguments are not declared, and the randn function is written alone, it will print only one random value. We can also mention the size we wish to give in function; it can be single dimensional or multi–dimensional. Along with size, we can also mention what kind of distribution we want, single or double or distributed.

Syntax:

<!-- wp:paragraph -->
<p><code>Value 1 = randn<br>Variable name = randn</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>Value 1 = randn(5)<br>Variable name = randn (no. of rows and columns)</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>Value 1 = randn (1 ,3)<br>Variable name = randn (no. of rows , no. of columns)</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>Value 1 = randn (1, 3, 2)<br>Variable name = randn (no. of rows, no. of columns, no of matrices)</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>Value 1 = randn (2, 'single')<br>Variable name = randn (no. of rows and columns, ‘type’)</code></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><code>Value 1= randn ( Dim )<br>Variable name = randn (size)</code></p>
<!-- /wp:paragraph -->

Value 1 = 2 + i * randn
Variable name = Integer + complex variable * randn

How randn Function Work in Matlab?

  • randn functions work on random values as it provides random numeric values to the user.ir creates random values of any type like integers, floating numbers, complex numbers, etc.
  • By default, randn create only one random value, and as per arguments, it can create multiple values.
  • In this function inside the brackets, we can give dimensions of output; it can be single dimension or multi-dimension.
  • Values are distributed as per the user’s requirements.

Examples of Matlab randn

Given below are the examples of Matlab randn:

Example 1:

Let us consider one simple example; in this example, value 1 is an input variable that stores random values. There are no arguments passed through the function so that it will print only one value illustrated in an example. If we write the randn function repeatedly in the same code, it will print different random values. For example, a function written three-time therefore, it gives three random values as output.

Code:

clc ;
clear all ;
disp('Output');
Value1 = randn

Output:

Matlab randn 1

Code:

clc ;
clear all ;
disp ('Output');
Value1 = randn
Value2 = randn
Value3 = randn

Output:

Matlab randn 2

Example 2:

In this example, we will see dimensions as arguments in randn function. For example, we can see one value is passed through a function. If there is only one value present inside the brackets, then it represents a number of rows as well as a number of columns of the output matrix. Therefore output dimensions are two by two and four by four. For example, there are two values written inside the brackets. This first value represents a number of rows, and the second value represents a number of columns. And there are three values present inside the function brackets; the first value represents a number of rows, the second value represents a number of columns, and the third value represents a number of matrices illustrated in the example.

Code:

clc ;
clear all ;
disp('Output');
Value1 = randn(2)
Value2 = randn(4)

Output:

Matlab randn 3

Code:

clc ;
clear all ;
disp('Output');
Value1 = randn (1,3)
Value2 = randn (4,2)

Output:

Matlab randn 4

Code:

clc ;
clear all ;
disp ('Output');
Value1 = randn (1, 3, 2)
Value2 = randn(3, 1, 2)

Output:

Matlab randn 5

Example 3:

Example three shows the type of data we wish to create. Along with dimensions, we can also mention the type of input we want in output like single, distributed or double, which is illustrated in the example. If we perform matrix operation, then as per the rule, all the matrices should be of the same size; therefore, to maintain the size of a matrix, we can use ‘size’ syntax in the randn function, which is shown in the example.

Code:

clc ;
clear all ;
disp('Output');
Value1 = randn(2, 'single')
Value2 = randn (3, 'distributed')

Output:

shows type of data we wish to create

Code:

clc ;
clear all ;
disp('Output');
Value1 = randn( 2,'single')
Value2 = randn (2 ,'double')

Output:

Command Window

Code:

clc ;
clear all ;
disp('Output');
Input = [ 4,3; 2,2; 4,7] Dim = size (Input)
Value1= randn (Dim)

Output:

Matlab randn 8

Example 4:

In the previous example, input data were real numbers, but we can also work on complex numbers in randn function. In this example, we multiply by the complex variable ‘i’ to create a number as a complex number. As well as we performed an operation on random numbers, this is illustrated.

Code:

clc ;
clear all ;
disp('Output');
Value1 = 2+ i * randn
Value2 = randn + i * randn

Output:

we multiply by complex variable ‘i’
Categories
1. Basics of Matlab

Matlab xticks

The ‘xticks function’ is used in Matlab to assign tick values & labels to the x-axis of a graph or plot. By default, the plot function (used to draw any plot) in Matlab creates ticks as per the default scale, but we might need to have ticks based on our requirement. Adding ticks as per our need and labelling them make the plots more intuitive and easier to understand. For this, we can use the xticks function along with the xticklabels function in Matlab to identify the values of our choice on the plots easily.

Syntax of xticks function:

xticks (A)

xticks (A : B : C)

Explanation:

  • xticks (A) is used to set the ticks defined by the vector A. Please note that A must have values in the ascending order.
  • xticks (A: B: C) is used to set the ticks defined by the range A: C, with a B gap between the ticks.

Examples of Matlab xticks

Given below are the examples of Matlab xticks:

Example 1:

In this example, we will use the plot function to plot a sine wave and then will set the ticks for it using the xticks function.

Below are the steps to be followed:

  • Write the code to create a sine wave.
  • Use the xticks function to set the ticks for the x-axis.
  • Use the xticklabels function to set the labels for the ticks defined in the above step.

Code:

<!-- wp:paragraph -->
<p>A = 0 : pi/50 : 2*pi;<br>[Initializing the range for sine wave]</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>B = sin (A);<br>[Initializing the sine wave]</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>plot (A, B)<br>[Using the plot function to plot the sine wave]</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>xticks ([0 3 6])<br>[Using the xticks function to set the ticks for the x-axis]</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>xticklabels ({‘A = 0′,’A = 3′,’A = 6’})<br>[Using the xticklabels function to set the labels for the ticks]</p>
<!-- /wp:paragraph -->

Input:

Matlab xticks 1

Output:

plot a sine wave

As we can see in the output, we have obtained ticks of our choice, i.e. 0, 3, 6, using the xticks function. We have also set the labels for these ticks using the xticklabels function.

Example 2:

In this example, we will use the plot function to plot a cos wave and then will set the ticks for it using the xticks function.

Below are the steps to be followed:

  • Write the code to create a cos wave.
  • Use the xticks function to set the ticks for the x-axis.
  • Use the xticklabels function to set the labels for the ticks defined in the above step.

Code:

<!-- wp:paragraph -->
<p>A = 0 : pi/100 : 3*pi;<br>[Initializing the range for cos wave]</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>B = cos (A);<br>[Initializing the cos wave]</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>plot (A, B)<br>[Using the plot function to plot the cos wave]</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>xticks ([0 3 6 9])<br>[Using the xticks function to set the ticks for the x-axis]</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>xticklabels ({‘A = 0′,’A = 3′,’A = 6’, ‘A = 9’})<br>[Using the xticklabels function to set the labels for the ticks]</p>
<!-- /wp:paragraph -->

Input:

Matlab xticks 3

Output:

plot a cos wave

As we can see in the output, we have obtained ticks of our choice, i.e. 0, 3, 6, 9, using the xticks function. We have also set the labels for these ticks using the xticklabels function.

In the above 2 examples, we have passed all the values which we want to set as the ticks of a plot as arguments to the xticks function.

Next, we will see how to set a range of values with a fixed interval as the ticks of a plot.

Example 3:

In this example, we will use the plot function to plot a sine wave and then will set the ticks for it by passing a range as an argument to the xticks function.

Below are the steps to be followed:

  • Write the code to create a sine wave.
  • Use the xticks function to set the ticks for the x-axis.
  • Use the xticklabels function to set the labels for the ticks defined in the above step.

Code:

<!-- wp:paragraph -->
<p>A = linspace (0, 50)<br>[Initializing the range for sine wave]</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>B = sin (A);<br>[Initializing the sine wave]</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>plot (A, B)<br>[Using the plot function to plot the sine wave]</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>xticks ([0 : 10 : 50])<br>[Using the xticks function to set the ticks for the x-axis]</p>
<!-- /wp:paragraph -->

Input:

Matlab xticks 5

Output:

to plot a sine wave

As we can see in the output, we have obtained ticks of our choice by passing a range as an argument to the xticks function.

Categories
1. Basics of Matlab

Heatmap in MATLAB

Do you know what is a heat map and for what purpose it is good? First of all, let’s introduce what is MATLAB? MATLAB is a registered and high-performance programming language developed by Math Works. MATLAB is aimed for technical calculating. It allows matrix operations, the plotting of functions and data, and the execution of algorithms. Further, Heatmap in MATLAB also helps to produce user interfaces that interface with programs written in other languages, comprising C, C++, Java, FORTRAN, and Python. Now we can defineHeatMap Basically,

“Heatmap is Matlab software for graphical representation of data where color-coded systems are used. ” The objective of Heat Maps to visualize the volume of locations or events in a better way within a dataset. It also helps in directing audiences towards the areas on data visualizations.

We use a heat map chart which is a particular chart that represents data values in the table with the help of colors. This is applicable when we have to design large and complex data. Heatmap works by saving the data from a web page. Suppose if any part of a web page gets more attention or if the contents on the webpage are clicked frequently then, heatmap uses a dark-to-light color to represent it.

For example, the contents are displayed with a dark color which is viewed more and the other area with no attention from visitors is displayed by light color.

How to Create Heatmap in MATLAB?

Since we know that MATLAB is a language deliberated for mathematical and scientific purposes that has many tools to deal with most areas of Maths and Science. It enhances computation, visualization, and programming in an easy-to-use environment. This allows the problems and solutions to be conveyed in a familiar mathematical representation.

Therefore, now let’s talk about HEATMAP in MATLAB; Heatmap is useful to display a matrix as an image whose color intensities give the magnitude of its values. Also, it empowers you to identify the following things:

  • X-axis and Y-axis tick labels:

To Show the row or column directories or any other numeric or text markers. Here, X-axis tick labels can be interchanged.

  • Text labels:

Connects the heatmap image with the help of organized text labels. We can switch the font size and font color of the labels. But the labels while zooming, panning or resizing the figure can be updated automatically.

  • Custom color maps:

To specify your own colors, we can use MATLAB’s default color maps. Also, we can have different color maps for different heat maps in a figure.

Other parameters are such as grid lines, color bars for configuration while` preparing Heatmap.

Those who are familiar with Matlab and knows how it works and the coding part they have a plus point to study Heatmap with ease. They have an interest in graphical representation and can understand the Heatmap process more easily as well as the functions.

Syntax to Create a Heatmap chart

The Basic Syntax Functions are given below:

h = heatmap (htbl,xvar,yvar)
h = heatmap (htbl,xvar,yvar,'ColorVariable',cvar)
h = heatmap (cdata)
h = heatmap (xvalues,yvalues,cdata)
h = heatmap (___,Name,Value)
h = heatmap (parent,___)

Explanation of these functions

  • The xvar is the table variable that displays along the x-axis. The yvar (input) is the table variable that displays along the y-axis. The colors are created on a count combination. Then it is used to change the heatmap once it is formed.
  • The function h = heatmap (htbl,xvar,yvar) generates a heatmap from the table htbl and provides the object of the Heatmap Chart.
  • The function h = heatmap (htbl,xvar,yvar,color variable’,cvar) is used to determine the color data using the table variable identified by cvar. Here, the mean combination is the basic calculation method.
  • The Function h = heatmap (data) is useful to create a heatmap from the matrix. For a single value in data, the heatmap has only one cell.
  • The function h = heatmap (xvalues,yvalues,cdata) determines values for the labels which is shown along x-axis and y-axis.
  • The function h = heatmap (___, Name, Value) identifies more possibilities for the heatmap that uses single or multiple names or values couple arguments.
  • The function h = heatmap (parent,___) forms the heatmap in the section indicated by the parent.

Examples of Heatmap in MATLAB

Given below are the examples of Heatmap MATLAB:

Example 1:

Build a heatmap from a table of data for sports students

Firstly, we will load the students’ data set. Then make a table from a subset of the variables which is loaded into the workspace. After this, we generate a heatmap that totals the number of students having a matching set of Skilled and Fresher values.

Code:

load students
htbl = table (Name,Age,Gender,Fresher,...
Skilled,Weight,Location);
h = heatmap (htbl,'Skilled','Fresher');

Output:

heatmap in matlab

Example 2:

Make Heatmap from a Matrix Dataset

Generate a matrix of a dataset. Now, produce a heatmap of the values from the matrix. So, the labels along the x-axis and y-axis seem to be 1, 2, 3,.., etc.

Code:

cdata = [40 50 30; 41 52 70 ; 31 90 65; 20 90 55] ;
h = heatmap (cdata);

Output:

heatmap in matlab

Example 3:

Make Heatmap By Custom Axis Labels from Matrix Dataset

Firstly, we make a matrix of a dataset. Again generate a heatmap of the values. We will apply custom labels along the x-axis & y-axis and indicate the first two arguments to be labeled. Using the setting properties of the Heatmap Chart object, we need to identify the title and labels of an axis.

Code:

cdata = [40 50 30; 41 52 70 ; 31 90 65; 20 90 55] ;
xvalues = {'Banarsi','Silk','Cotton'};
yvalues = {'Yellow','Red','Pink','Green'};
h = heatmap (xvalues,yvalues,cdata);
h.Title = 'Saree Orders';
h.XLabel = 'Types';
h.YLabel = 'Colors';

Output:

By Custom Axis Labels from Matrix Dataset
Categories
1. Basics of Matlab

Magnitude of Vector

The definition of magnitude of vector Matlab is a quantity with both direction and magnitude called a vector. In the study of motion these both vector quantities play a very important role. Force, velocity, acceleration, displacement and momentum are the some of examples of vector quantities. The magnitude of a vector is that the length of the vector s. The magnitude of the vector is denoted as ∥b∥.

Syntax of Matlab Magnitude of Vector

You can use the following syntaxes to generating a magnitude vector:

u1 = [ 1 : 2 : 22 ] ;

su1 = u1 .* u1 ;

p1 = sum ( su1 ) ;

mag1 = sqrt ( p1 )

el = abs(D)

  • el = abs(D) returns the absolute value of each element in array D.
  • If D is complex, abs(D) returns the complex magnitude.

How to do Magnitude of Vector Matlab?

Magnitude of a vector u with elements u1, u2, u3, …, un, is given by the equation:| u | = √ ( u12 + u22 + u32 + … + un)

You need to take the following steps to calculate the magnitude of a vector:

  • Take the product of the vector with itself, using array multiplication( .* ). This produces a vector su, whose elements are squares of the elements of vector u.
  • Use the sum function to get the sum of squares of elements of vector u. This is also called the dot product of vector u.
  • Use the sqrt function to get the square root of the sum, which is also the magnitude of the vector u.

The magnitude of a Vector Formula:

Suppose DB is a vector quantity that has magnitude and direction both. To calculate the magnitude of the vector DB, we have to calculate the distance between the initial point D and endpoint B. In the X-Y plane, let D has coordinates (x0,y0) and B has coordinates (x1,y1).

Therefore, by distance formula, the magnitude of vector →DB can be written as:|→DB| =√ (x1–x0)2+(y1–y0)2

Now, if the endpoint B is at the origin, then the magnitude of a vector formula becomes:|→DB| = √x2+y2

Matlab Magnitude of Vector 1

Examples of Matlab Magnitude of Vector

Given below are the examples of Matlab Magnitude of Vector:

Example 1:

Let us consider one example; in this example, we can create one vector, ‘u’. Then we take a dot product (.*) of vector u with itself. This produces a vector ‘su’ whose elements are square of the element of vector u. Then we use the sum function to get the sum of the square of elements of vector u. Then we use the square root function to get a magnitude of vector u and display it by using the disp function.

Code:

clc ;
clear all ;
u = [ 2 : 4 : 22 ] ;
su = u .* u ;
p = sum ( su ) ;
mag = sqrt ( p ) ;
disp ( ' Magnitude :-  ' );
disp ( mag );

Output :

Matlab Magnitude of Vector 2

Example 2:

Let us one another example; in the first example, we can only display vector magnitude value. But in this example, we can also plot the graph for the vector magnitude. For that, we can first create one vector u1. Square the vector u1 by taking the dot product of vector u1 with itself, and the resultant will be stored in su1. Then using the sum function, we can sum of the square of the element vector u1. And then, using the sqrt function, we get the magnitude. For the plotting the graph, we will use the plot inbuilt function in Matlab. For this function, we can first decide the time scale as per requirement; let us assume the time scale be 0: 0.1:10. Then we can use the plot function with time and magnitude (mag) to see the graph.

Code:

clc ;
clear all ;
close all ;
time = 0: 0.1:10;
u1 = [ 1 : 2 : 22 ] ;
su1 = u1 .* u1 ;
p1 = sum ( su1 ) ;
mag1 = sqrt ( p1 ) ;
disp ( ' Magnitude :-  ' );
disp ( mag1 );
plot ( time , mag1 );

Output:

create one vector u1

Example 3:

Let us see one another example, to create Absolute value and complex magnitude using vector magnitude. Create a numeric vector of real values ( Absolute Value of Scalar).

Code:

clc;
clear all;
y = abs(-3)
x = [4.3 -3.56 6.23 -5 -0.02];
y = abs(x)

Output:

to create Absolute value and complex
Categories
1. Basics of Matlab

Matlab hold on

The following article provides an outline for Matlab hold on. Matlab’s ‘hold’ command determines whether the newly created graphic object will be added to the existing graph or will it replace the existing objects in our graph. The command ‘hold on’ is used to retain our current plot & its axes properties in order to add subsequent graphic commands to our existing graph.

For example, we can add 2 trigonometric waves, sine and cos, to the same graph using the hold on command.

Syntax:

  • Command ‘hold on’ is used to retain the plot in current axes. By doing so, the new plot is added to the existing axes without making any changes to the existing plot.
  • Command ‘hold off’ is used to change the hold on state back to off.

Examples of Matlab hold on

Let us see how to add a new plot to the existing axes in Matlab using the ‘hold on’ command.

Example 1:

In this example, we will use the ‘hold on’ command to add 2 plots to a single graph. We will plot 2 different logarithmic functions in one graph for our 1st example.

The steps to be followed for this example are:

  • Initialize the 1st function to be plotted.
  • Use the plot method to display the 1st function.
  • Use the ‘hold on’ command to ensure that the plot of the next function is added to this existing graph.
  • Initialize the 2nd function to be plotted.
  • Use the plot method to display the 2nd function.
  • Use the ‘hold off’ command to ensure that the next plot, if any, is added as a new graph.

Code:

x = linspace (0, 5);

y = log (5* x);[Initializing the 1st logarithmic function]

plot (x, y)[Using the plot method to display the figure]

hold on

x = linspace (0, 5);

z = log (3 * x);[Initializing the 2nd logarithmic function]

plot(x, z)[Using the plot method to display the figure]

hold off[Using the ‘hold off’ command to ensure that the next plot, if any, is added as a new graph]

This is how our input and output will look like in the Matlab command window.

Input:

Matlab hold on 1

Output:

Matlab hold on 2

As we can see in the output, we have obtained 2 logarithmic functions in the same graph as expected by us.

Example 2:

In this example, we will use the ‘hold on’ command to add 2 different exponential functions in one graph.

The steps to be followed for this example are:

  • Initialize the 1st function to be plotted.
  • Use the plot method to display the 1st function.
  • Use the ‘hold on’ command to ensure that the plot of the next function is added to this existing graph.
  • Initialize the 2nd function to be plotted.
  • Use the plot method to display the 2nd function.
  • Use the ‘hold off’ command to ensure that the next plot, if any, is added as a new graph.

Code:

x = linspace(0, 5);

y = exp(2* x);[Initializing 1st exponential function]

plot(x, y)[Using the plot method to display the figure]

hold on

x = linspace(0, 5);

z = exp(2.1 * x);[Initializing 2nd exponential function]

plot(x, z)[Using the plot method to display the figure]

hold off[Using the ‘hold off’ command to ensure that the next plot, if any, is added as a new graph]

This is how our input and output will look like in the Matlab command window.

Input:

Matlab hold on 3

Output:

to add 2 different exponential functions

As we can see in the output, we have obtained 2 exponential functions in the same graph as expected by us.

In the above 2 examples, we saw how to add 2 functions to a single graph. We can also use the same ‘hold on’ command to add more than 2 functions also. Next, we will see how to add 3 functions to the same graph.

Example 3:

In this example, we will use the ‘hold on’ command to add 3 plots to a single graph. We will plot 3 different exponential functions in one graph for this example.

The steps to be followed for this example are:

  • Initialize the 1st function to be plotted.
  • Use the plot method to display the 1st function.
  • Use the ‘hold on’ command to ensure that the next plot is added to this existing graph.
  • Initialize the 2nd function to be plotted.
  • Use the plot method to display the 2nd function.
  • Use the ‘hold on’ command to ensure that the next plot is added to this existing graph.
  • Initialize the 3rd function to be plotted.
  • Use the plot method to display the 3rd function.
  • Use the ‘hold off’ command to ensure that the next plot, if any, is added as a new graph.

Code:

x = linspace(0, 5);

y = exp(2* x);[Initializing 1st exponential function]

plot(x, y)[Using the plot method to display the figure]

hold on

x = linspace(0, 5);

z = exp(2.1 * x);[Initializing 2nd exponential function]

plot(x, z)[Using the plot method to display the figure]

hold on

x = linspace(0, 5);

a = exp(2.2 * x);[Initializing 3rd exponential function]

plot(x, a)[Using the plot method to display the figure]

hold off[Using the ‘hold off’ command to ensure that the next plot, if any, is added as a new graph]

This is how our input and output will look like in the Matlab command window:

Input:

Matlab hold on 5

Output:

plot 3 different exponential functions

As we can see in the output, we have obtained 3 exponential functions in the same graph as expected by us.

Categories
1. Basics of Matlab

Matlab Append

Matlab append method can be used to append a string and add another string to it. This method is very handy when combining multiple strings and getting a single string as the output.

For example, if we take 2 strings, ‘First Name’ and ‘Last Name’, as inputs from the user, later there might be a possibility that we need to combine these 2 strings and get a single string which will give us the full name. This is where we use the append method in Matlab.

Syntax:

  • NewString = append (string1, string2, …. stringN) is used to combine various strings in Matlab. The strings will be combined in the same order as they are passed as arguments.
  • As it is evident from the syntax, we can combine multiple strings using the append method.

Examples of Matlab Append

Given below shows how to combine strings in Matlab using the append method:

Example 1:

In this example, we will use the append method to combine 2 strings.

The steps to be followed for this example are:

  • Initialize the strings that are to be combined.
  • Pass the above strings as arguments to the append function.

Code:

  1. string1 = “MATLAB”

[Initializing the 1st string]

  1. string2 = “Append”

[Initializing the 2nd string]

  1. NewString = append(string1, string2)

[Passing the above 2 strings to the append method. Please note that the order of arguments must be the same in which we want the strings to be combined]

This is how our input and output will look like in the Matlab command window:

Input:

Matlab Append 1

Output:

Matlab Append 2

As we can see in the output, we have obtained a string that combines string1 and string2.

In the above example, we saw that the 2 input strings were combined, but there was no space between them in the final output.

Next, we will see how to add a space or any special character between 2 strings.

Example 2:

In this example, we will use the append method to combine 2 strings with a space between them.

The steps to be followed for this example are:

  • Initialize the strings that are to be combined.
  • Add an extra space at the beginning of the 2nd string.
  • Pass the above strings as arguments to the append function.

Code:

  1. string1 = “MATLAB”

[Initializing the 1st string]

  1. string2 = “ Append”

[Initializing the 2nd string. Please note that we have added an extra space at the beginning of string2. This is done to get a space in the combined string]

  1. NewString = append(string1, string2)

[Passing the above 2 strings to the append method. Please note that the order of arguments must be the same in which we want the strings to be combined]

This is how our input and output will look like in the Matlab command window:

Input:

combine 2 strings with a space between them

Output:

Matlab Append 4

As we can see in the output, we have obtained a string that combines string1 and string2. If we compare this output with the output in example 1, we will notice that now we have a space between two strings.

In the above examples, we combined 2 strings; next, we will see to combine more than 2 strings using the append method.

Example 3:

In this example, we will use the append method to combine multiple strings with a space between them.

The steps to be followed for this example are:

  • Initialize the strings that are to be combined.
  • Add an extra space at the beginning of all the strings, except the first one.
  • Pass the above strings as arguments to the append function.

Code:

  1. string1 = “Let”

[Initializing the 1st string]

  1. string2 = “ us”

[Initializing the 2nd string. Please note that we have added an extra space at the beginning of string2. This is done to get a space in the combined string]

  1. string3 = “ learn”

[Initializing the 3rd string. Again, there is an extra space]

  1. string4 = “ MATLAB”

[Initializing the 4th string]

  1. NewString = append(string1, string2, string3, string4)

[Passing the above 4 strings to the append method. Please note that the order of arguments must be the same in which we want the strings to be combined]

This is how our input and output will look like in the Matlab command window:

Input:

to combine multiple strings with a space between them

Output:

Matlab Append 6

As we can see in the output, we have obtained a string that combines all the input strings.

Example 4:

In this example, we will use the append method to combine string arrays of vectors. These character vectors are combined element by element.

The steps to be followed for this example are:

  • Initialize the string arrays that are to be combined.
  • Pass the above string arrays as arguments to the append function.

Code:

  1. Names = [“John” “Sam” “Mark” “Vince”]

[Initializing the 1st string array]

  1. Department = [“ HR” “ Finance” “ Operations” “ Marketing”

[Initializing the 2nd string array]

  1. NewString = append(Names, Department)

[Passing the above 2 string arrays to the append method. Please note that the order of arguments must be the same in which we want the arrays to be combined]

This is how our input and output will look like in the Matlab command window:

Input:

combine string arrays of vectors

Output:

Matlab Append 8

As we can see in the output, we have obtained the combination of 2 string arrays.

Categories
1. Basics of Matlab

Matlab log

Matlab log method can be used to compute the natural logarithm or common logarithm of any number. It can also be used to compute the natural logarithm or common logarithm of an array of numbers or a matrix of numbers. Please keep in mind that a natural logarithm has “e” as its base, where “e” represents Euler’s number and has a value of 2.71828, and a common logarithm has 10 as its base.

Syntax:

  • A = log (Number) is used to compute the natural logarithm (base “e)” of a number in Matlab. In the case of an array, we will get the natural logarithm of every element in the array.
  • A = log10 (Number) is used to compute the common logarithm (base 10) of a number in Matlab. In the case of an array, we will get the common logarithm of every element in the array.

Examples of Matlab log

Given below shows how to compute the natural logarithm in Matlab using the log method:

Example 1:

In this example, we will use the log method to compute the natural logarithm of a number.

The step to be followed for this example is:

  • Pass the number whose natural logarithm is required as an argument to the log method.

Code:

log(4)[Passing 4 as an argument to the log method as we need its natural logarithm] [Mathematically, the log of 4 to the base “e” is 1.3863]

This is how our input and output will look like in the Matlab command window:

Input:

Matlab log 1

Output:

Matlab log 2

As we can see in the output, we have the log of 4 to the base “e” as 1.3863, which is the same as expected by us.

Example 2:

In this example, we will use the log method to compute the natural logarithm of the elements of an array.

The steps to be followed for this example are:

  • Initialize the array.
  • Pass the array as an argument to the log method.

Code:

A = [3 6 4 8 6 1] [Initializing the array whose natural logarithm is to be computed]

log(A)[Passing the array as an argument to the log method]

This is how our input and output will look like in the Matlab command window:

Input:

Matlab log 3

Output:

matlab log 4

As we can see in the output, we have obtained the log of all the elements in the array’ to the base “e”, as expected by us.

Example 3:

In this example, we will use the log method to compute the natural logarithm of the elements of a matrix.

The steps to be followed for this example are:

  • Initialize the matrix.
  • Pass the matrix as an argument to the log method.

Code:

A = [3 6 4; 8 6 1; 2 1 6] [Initializing the matrix whose natural logarithm is to be computed]

log(A)[Passing the matrix as an argument to the log method]

This is how our input and output will look like in the Matlab command window:

Input:

matlab log 5

Output:

compute the natural logarithm of the elements of a matrix

As we can see in the output, we have obtained the log of all the elements in the matrix to the base “e”, as expected by us.

In the above 3 examples, we have computed the natural logarithm of numbers using the log method.

Next, we will compute the common logarithm of numbers using the log10 method.

Example 4:

In this example, we will use the log10 method to compute the common logarithm of a number.

The step to be followed for this example is:

  • Pass the number whose natural logarithm is required as an argument to the log method.

Code:

log10(5)[Passing 5 as an argument to the log10 method as we need its common logarithm] [Mathematically, the log of 5 to the base “10” is 0.6990]

This is how our input and output will look like in the Matlab command window:

Input:

matlab log 7

Output:

compute the common logarithm of a number

As we can see in the Output, we have the log of 5 to the base “10” as 0.6990, which is the same as expected by us.

Example 5:

In this example, we will use the log10 method to compute the common logarithm of the elements of an array.

The steps to be followed for this example are:

  • Initialize the array.
  • Pass the array as an argument to the log10 method.

Code:

A = [4 7 1 3 6 2] [Initializing the array whose common logarithm is to be computed]

log10(A)[Passing the array as an argument to the log10 method]

This is how our input and output will look like in the Matlab command window:

Input:

matlab log 9

Output:

we will use the log10 method to compute the common logarithm

As we can see in the output, we have obtained the log of all the elements in the array to the base “10”, as expected by us.

Example 6:

In this example, we will use the log10 method to compute the common logarithm of the elements of a matrix.

The steps to be followed for this example are:

  • Initialize the matrix.
  • Pass the matrix as an argument to the log10 method.

Code:

A = [2 5 4; 1 6 3; 6 3 7] [Initializing the matrix whose common logarithm is to be computed]

log10(A)[Passing the matrix as an argument to the log10 method]

This is how our input and output will look like in the Matlab command window:

Input:

matlab log 11

Output:

compute the common logarithm of the elements of a matrix

As we can see in the output, we have obtained the log of all the elements in the matrix to the base “10”, as expected by us.

Categories
1. Basics of Matlab

ksdensity Function

In Matlab ‘ks density’ function is used to calculate probability density function response. This function works on arrays, vectors, and multidimensional data. Probability density function uses normal kernel function to calculate density. By applying above function we get density values as well as density response curve of function. The evaluation of function is perform on equally spaced points on x time interval axis. It calculates density at hundred points and nine hundred points for uni- variants sample and bi variants sample respectively. Along with instance value it accepts other arguments also like name, value, axis, and points.

Syntax:

  • [A, B] = ksdensity (input);

[Variable name 1, Variable name 2] = ksdensity (input variable name )

  • Ksdensity (input, A, 'Function', 'icdf' )

Ksdensity (input variable name, variable name 1, ’function’, ‘ icdf ’)

  • [A, B, Bandwidth] = ksdensity (input)

[Variable name 1, Variable name 2, Bandwidth] = ksdensity (input variable name )

How ksdensity function works in Matlab?

Density function has two different measures probability density function and cumulative density function. Probability density function can be achieved by integrating cumulative density function and cumulative density function can be achieved by differentiating probability density function. this function is used to interpret values at each given sample. we can pass multiple arguments through density function like density function, sample locations, bandwidth, input samples, CDF or pdf. to apply function initially we need to create input of continuous values or samples then only we can apply ksdensity function.

Examples

Let us discuss examples of Matlab ksdensity.

Example 1:

To apply ksdensity function first we need to create sample database, here we have created input sample data which is declared as ‘input’. Input is a combination of two normal random distribution. Random normal distribution is created by using randn function. first random function will give 25 by 1 matrix random values and second random function will give 10 by 1 matrix random value. this function will trace all the value in a range of input .here ‘A’ is probability density function and this function estimation is based on points ‘B’.

Code:

clc ;
clear all ;
disp ('output')
input = [randn(25, 1); randn(10, 1)];
[ A, B ] = ksdensity (input);
figure
plot (B, A);

Output :

Matlab ksdensity 1

Example 2:

In this example, we will use another function inside ksdensity function. Initially, input samples are declared by the variable name ‘input’. Input is created by line space function which will create rows of vectors from 1 to 200. line space will create array or vector by pacing of sample 1.then we have used ksdensity function with multiple arguments we are passing input and A to the function. Input is created by combining two random functions; first random function will create samples in rage of fifty to 1 that means matrix of fifty by one and second random function will create random samples in range of ten to 1 that means matrix of ten by one. here ‘A’ is probability density function and this function estimation is based on points in input. Along with these two parameter other parameter pass through the function are ‘function and icdf’. Here function is keyword for ‘icdf’ and icdf is inverse cumulative distributed function which will perform inverse operation of cumulative distribution function.

Code:

clc ;
clear all ;
disp ('output')
input = [randn(50, 1); randn(10, 1)];
A = linspace(.1, 1, 200);
figure
ksdensity (input, A, 'Function', 'icdf');

Output:

Matlab ksdensity 2

Example 3:

In this example, we will consider one more new term which is bandwidth. Bandwidth specifies how much sample rate passed through function. Here we have created input sample data which is declared as ‘input’. Input is a combination of two normal random distribution. Random normal distribution is created by using randn function. First random function will give fifteen by one matrix random value and second random function will give fifty by one matrix random value. this function will trace all the value in range of input .here ‘A’ is probability density function and this function estimation is based on points ‘B’. we are giving format of three variables to the function so automatically ksdensity function will return values of A, B, and Bandwidth.

Code:

clc ;
clear all ;
disp ('output')
input = [randn(15, 1) ; randn(50, 1)];
[ A, B, Bandwidth] = ksdensity (input);
Bandwidth
figure
plot (B, A);
xlabel ('A')
ylabel ('B')
hold on

Output:

Matlab ksdensity 3
Categories
1. Basics of Matlab

Exponential in Matlab

In day to day life, we need mathematics. There are lots of functions in mathematics and exponential is one of the important functions. Many times there is a need for exponential values of the data. To get the exponential value in Matlab we used an exponential statement. As well as in some cases there is a need to plot the exponential graph. So for that first, we had exponential data and this is possible in MATLAB by using exponential statement.

Syntax:

The syntax for Exponential in Matlab is as shown below:

  • y1 = exp(x1)

How to do Exponential in Matlab?

For Exponential plotting of the data, we use exp and plot statements.

The steps for Exponential plotting of the data using exp and plot statement:-

Step 1: we take variables and assign values.

Step 2: then we use exp to get exponential values of the variable.

Step 3: then we use a plot statement with appropriate syntax to plot the exponential graph to visualize the exponential data.

Examples

Let us discuss examples of Exponential in Matlab.

Example 1:

Let us see an example related to exponential in Matlab, for exponential we use a Matlab syntax as ‘exp’, exp in parenthesis we take that variable names or we directly take the equation for exponential. In this example, we display the exponential signal also using a plot function. Firstly we take a range of axis -5 to 15 with a difference of 0.5, this range we take in an x1 variable. Then we write an exponential equation using exp function, we take an exp in parenthesis x1 is divided by 4 and these exponential values are assigned to variable y1, the equation is y1 = ex1/4, the value of x1 is varied from -5 to 15 and according to that the different values are assign to y1 variable. Then we plot a signal using x1 and y1 variable and plot function, plot is an inbuilt function available on Matlab it is plots the data in y1 versus the corresponding values in x1, x-axis is x1 which is varying from -5 to 15 comma y-axis is a function of x1. And this is an exponential signal related to the given equation.

Matlab code for example 1-

clc;
clear all;
close all;
x1 = -5 : 0.5 : 15 ;
y = exp ( x1 / 4 );
plot ( x1 , y )
title ( ' Exponential ' );

Output:

Exponential in Matlab 1

Example 2:

Let us see an example for exponential in Matlab, the exponential signal is defined as x1of n1 is equal to alpha (a1) power n1 U of n1. Where alpha is the rate at which exponential signal is increasing or decreasing n1 is an independent variable which is varying from minus infinity to plus infinity so therefore there aretwo parameters are here one is alpha and another one is independent variable n1 let me define those two, n1 is usually varying from minus infinity to plus infinity but since we cannot reach infinity so will start with -150 to 150 in steps of 1. Now we define a1 as equal to 0.98 this is my alpha, there is a condition that is if alpha is greater than 1 the signal x1 of n1 is exponentially increasing if alpha (a1) is in between 0 to 1 then the signal x1 of n is exponentially decreasing signal, so our example the value of alpha is 0.98 so it will give me exponentially decreasing signal. Now define x1 of n1 is equal to alpha dot power n1 and then stem, stem for discrete signal, the x-axis is n1 which is varying from -150 to 150 comma y-axis is a function of n1.

Matlab code for example 2:

clc;
clear all;
close all;
n1 = -150 : 1 : 150 ;
a1 = 0.98;
x1 = a1 .^ n1;
stem (n1 , x1);
title ( ' Exponential ' );

Output:

Exponential in Matlab 2

Example 3:

Let us see an example related to exponential in Matlab, for exponential we use a Matlab syntax as ‘exp’, exp in parenthesis we take that variable names or we directly take the equation for exponential. Firstly we take a range of axis -5 to 20 with a difference of 1, this range we take in an x1 variable. Then we write the exponential equation using exp function, we take an exp in parenthesis x1 is multiply by 2 and these exponential values are assigned to variable y1, the equation is y1 = e^x, the value of x1 is varied from -5 to 20 and according to that the different values are assigned to y1 variable. Then we plot a signal using x1 and y1 variable and stem function, stem is an inbuilt function available on Matlab it is plot district signal for the data in y1 versus the corresponding values in x1, the x-axis is x1 which is varying from -5 to 20 comma y-axis is a function of x1. And this is an exponential signal related to a given equation. And then we take a title function to give a title to that figure.

Matlab code for example 3:

clc ;
clear all ;
close all ;
x1 = -5 : 1 : 20 ;
y1 = exp (x1 ) ;
stem ( x1 , y1 )
title ( ' Exponential plot ' ) ;

Output:

Categories
1. Basics of Matlab

Matlab ones

Matlab one’s function is used to get a scalar or a vector with all ‘ones’ (1s) as its elements. Loops like ‘while’ & ‘for’ increase the size of our data structure incrementally every time a loop is executed. This process adversely affects the performance of the program. Resizing arrays repeatedly requires extra time seeking bigger contiguous memory blocks & then placing the arrays into these blocks. Functions like Matlab ones are used to improve code performance by pre-allocating the space required for the input array.

Syntax of Function ‘ones’ in Matlab:

A = ones

A = ones (n)

A = ones (size 1, size 2, size 3, ….)

Description:

  • A = ones will return scalar 1 as output.
  • A = ones (n) will return a square matrix of order n X n.
  • A = ones (size 1, size 2, size 3, ….) will return a matrix of required dimensions.

Examples of Matlab ones

Given below are the examples of Matlab ones:

Example 1:

In the first example, we will use ‘one’s function’ to create a square matrix of order 3 with all 1s as its elements.

Below are the steps that we will follow for this example:

  • First, pass the required order as an argument to the one’s function.
  • Display the output.

Code:

A = ones(3)[Using ‘ones function’ with ‘3’ as the argument. Please note that we have passed ‘3’ as an argument because we need the matrix with 1s to be of order 3 x 3 ]

A[Displaying the output]

This is how our input and output will look like in the Matlab command window:

Input:

A = ones(3)
A

Output:

Matlab ones 1

As we can see in the output, the function ‘ones’ has given us a matrix of order 3 and with 1s as its elements.

Example 2:

In this example, we will use one function to create a square matrix of order 4 with all 1s as its elements.

Below are the steps that we will follow for this example:

  • First, pass the required order as an argument to the one’s function.
  • Display the output.

Code:

A = ones(4)[Using ones function with ‘4’ as the argument. Please note that we have passed ‘4’ as an argument because we need the matrix with 1s to be of order 4 x 4 ]

A[Displaying the output]

This is how our input and output will look like in the MATLAB command window.

Input:

A = ones(4)
A

Output:

function to create a square matrix

As we can see in the output, the function ‘ones’ has given us a matrix of order 4 and with 1s as its elements.

In the above 2 examples, we have used ‘ones function’ to create a square matrix of all ones. Next, we will see the syntax to create the matrix of the required order. i.e. a matrix which is not a square matrix.

Example 3:

In this example, we will use ‘ones function’ to create a matrix with all 1s as its elements and order 2 x 3 ( 2 rows and 3 columns).

Below are the steps that we will follow for this example:

  • First, pass the required order as an argument to the ones function.
  • Display the output.

Code:

A = ones(2, 3)[Using ones function with ‘2’ and ‘3’ as the arguments. Please note that we have passed 2, 3 as the arguments because we need the matrix with 1s to be of order 2 x 3 ]

A[Displaying the output]

This is how our input and output will look like in the MATLAB command window.

Input:

A = ones(2, 3)
A

Output:

Matlab ones 3

As we can see in the output, the function ‘ones’ has given us a matrix of order 2 x 3 and with 1s as its elements.

Example 4:

In this example, we will use ‘ones function’ to create a matrix with all 1s as its elements and order 3 x 4 ( 3 rows and 4 columns).

Below are the steps that we will follow for this example:

  • First, pass the required order as an argument to the ones function.
  • Display the output.

Code:

A = ones(3, 4)[Using ‘ones function’ with ‘3’ and ‘4’ as the arguments. Please note that we have passed 3, 4 as the arguments because we need the matrix with 1s to be of order 3 x 4 ]

A[Displaying the output]

This is how our input and output will look like in the MATLAB command window:

Input:

A = ones(3,4)
A

Output:

create a matrix with all 1s as its elements and order

As we can see in the output, the function ‘ones’ has given us a matrix of order 3 x 4 and with 1s as its elements.