0% found this document useful (0 votes)
2 views8 pages

Module 6 Ds

GNU Octave is a free-source tool primarily used for numerical calculations, particularly in data science for creating and testing numerical algorithms. The document covers the creation and manipulation of vectors and matrices, built-in functions for arithmetic operations, and various plotting techniques. It emphasizes the ease of use and efficiency of GNU Octave in handling numerical data and visualizations.

Uploaded by

shaurya4561999
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views8 pages

Module 6 Ds

GNU Octave is a free-source tool primarily used for numerical calculations, particularly in data science for creating and testing numerical algorithms. The document covers the creation and manipulation of vectors and matrices, built-in functions for arithmetic operations, and various plotting techniques. It emphasizes the ease of use and efficiency of GNU Octave in handling numerical data and visualizations.

Uploaded by

shaurya4561999
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

234 Fundamentals of Data Science

10
GNU Octave as a Data Science Tool

GNU Octave is a free-source application with a high-level programming


­language. GNU Octave is mainly used for numerical calculations. It is primar-
ily designed for matrix calculations such as decoding simultaneous equations,
calculating eigenvalues and eigenvectors, etc. As GNU Octave possesses its pro-
gramming language, it can present the data in many different ways. In the data
science domain, GNU Octave is used to create and test numerical algorithms.

FIGURE 10.2
10.1 Vectors and Matrices Defining vectors within a range.

Vectors column vector is defined by separating the numbers enclosed in the square
Numeric calculations normally consist of operating with number brackets by semicolons.
sequences. Such sequences of numbers are called arrays, but in GNU Octave, You can also create a vector of counting numbers using a colon “:”. To cre-
they are treated as a kind of vectors. A vector can be stated as a 1 × 1 matrix ate such a vector, define a range separated by a colon and enclosed in square
that encloses a number list. brackets as shown in Figure 10.2.
GNU Octave provides us with various ways to define a vector. Mostly, they You can also specify the increment factor within the range as shown in the
are defined using the square brackets “[ ]”. above figure.
As you can see in Figure 10.1, a row vector is defined by separating the Note that if a negative increment factor has to be given, the range should be
numbers enclosed in the square brackets by spaces or commas. Similarly, a given in a descending manner.
GNU Octave also has some in-built functions to create vectors. These func-
tions can be used to create a null matrix, an evenly spaced vector, and much
more. They are as follows:

FIGURE 10.3
FIGURE 10.1
linspace () example.
Defining vectors.

DOI: 10.1201/9780429443237-13 233


GNU Octave as a Data Science Tool 235 236 Fundamentals of Data Science

2. zeros (a1, a2, N) – This function creates a vector from 10a1 to 10a2
by logarithmically separating N elements in the vector. As shown
in Figure 10.4, a vector is created starting from 101 to 105, and all
the elements are logarithmically placed to create a vector with six
elements.

You can display the vector by just entering the vector name and extract the
elements of the vector by enclosing the element_index in the round brackets ().
To extract a range of elements, use the colon notation as shown in Figure 10.5.
Matrices
Matrices are the rectangular array elements and are represented to be
in size m × n, where m and n represent the number of rows and columns,
respectively. FIGURE 10.6
Matrix creation.
 2 4 3 
 
A = 8 6 5 
 12 24 6 

There are several ways to create a matrix in GNU Octave.


You can create a matrix using the same syntax as that of a vector just defin-
ing the row in different rows as shown in Figure 10.6.

FIGURE 10.7
FIGURE 10.4 Matrix multiplication.
logspace () example.

Another way to create a matrix is by using the semicolon notation.1


Enclose the entire matrix in the square brackets and separate the rows using
semicolons.
GNU Octave provides us with a way to create a matrix using the range of
values, i.e., using the colon notation. As shown in Figure 10.6, various ways
of the colon notation can be used at different rows.2
Matrix Multiplication
For matrices and vector multiplication, the * symbol is used to represent
the multiplication.
In matrix multiplication, it is important to remember that the matrices
can be multiplied only if they are compatible with each other. Compatible
matrices are the matrices in which the number of columns of the first matrix
matches with the number of rows of the second matrix. As shown in Figure
FIGURE 10.5
10.7, matrix a and matrix b are compatible with each other and thus can be
Extracting elements from a vector.
multiplied.
GNU Octave as a Data Science Tool 237 238 Fundamentals of Data Science

FIGURE 10.8 FIGURE 10.10


Matrix multiplication error. Matrix creation functions.

Some other functions that can be used for matrix manipulation are as follows:

FIGURE 10.9
Transpose of a matrix.

However, the matrices defined in Figure 10.8 cannot be multiplied as the


number of columns of the matrix (i.e., 3) is not equal to the number of rows in
matrix c (i.e., 2). The Octave prompt will throw an error when such matrices 10.2 Arithmetic Operations
are requested to be multiplied.3 GNU Octave provides various functions that are used to perform various
Transpose of a Matrix arithmetic operations on vectors or matrices. Many functions ease the user’s
A transposed matrix is a matrix whose original rows and columns are inter- job to perform arithmetic operations. However, we will discuss some of them
changed with one another.4 Usually, the transposed matrix is represented as in this chapter.6
ST. In GNU Octave, apostrophe (‘) is used to transpose a matrix (Figure 10.9).
GNU Octave provides various in-built functions that can be used for 1. exp(x) – This built-in function creates a vector/matrix which consists
matrix manipulation. We will discuss some of them in this chapter. of the exponential of every element in the vector/matrix x, i.e., it cal-
culates ex for all the elements in x (Figure 10.11).
1. zeros (M, N) – This function creates a matrix of size M × N which
consists of every element as a zero.
2. ones (M, N) – This function creates a matrix of size M × N which
consists of every element as one.

FIGURE 10.11
exp(x) example.
GNU Octave as a Data Science Tool 239 240 Fundamentals of Data Science

FIGURE 10.16
Example of trigonometric functions.

FIGURE 10.12
pow2(x) example.

FIGURE 10.13
pow2(f,x) example.

Note that GNU provides a lot of such in-built functions that make it easy to
perform arithmetic operations in GNU Octave.

FIGURE 10.14
10.3 Set Operations
sqrt(x) example. GNU Octave has many functions to manage huge datasets. A set is nothing
but a collection of distinctive elements of a vector or a matrix.1 A vector or a
matrix can be converted to a set just by removing the duplicate values using
the unique function.1 Moreover, it is not mandatory to use the unique func-
tion as all the set functions in GNU Octave removes the duplicate values
before operating.1

FIGURE 10.15
abs(x) example.
GNU Octave as a Data Science Tool 241 242 Fundamentals of Data Science

10.4 Plotting Data
The most basic plot in GNU Octave is created using the plot() function pro-
vided by GNU Octave. The plot() function takes the two inputs, i.e., the car-
tesian values x and y, and plots the graph. You can add specifications to the
graph by adding the title to the plot, the axis label, style of the plot, and much
more. One such graph is shown below where a sin(x) plot is plotted against x.
Octave:

1>x = 0:0.1:2*pi;
y = sin(x);
plot(x, y, "*r", "markersize", 2);
xlabel("x");
ylabel("y = sin(x)");
title("Basic plot example");

In this plot, we have used the “*” marker, but GNU Octave provides many
marker options. (We will discuss it further). The marker size is the size of the
marker.10,11 You can modify your plot according to the requirements of the
user (Figure 10.19).
The format arguments that can be used within the plot() function are given
as below:

Linestyle:

FIGURE 10.17
Example of the union and intersection of the set.

FIGURE 10.18
FIGURE 10.19
Example of setdiff(), setxor(), and ismember().
Basic plot example.
GNU Octave as a Data Science Tool 243 244 Fundamentals of Data Science

Marker12: Octave:2>

pie ([17, 52, 41,28,2], [0,3,0,0,0], {"Action", "Sci- Fi",


"Drama", "Romance", "Comedy"});
title ("Pie Chart for Favorite Movies")

In the above example, a pie chart for favorite movies is created using the
pie()function. You can see that the “Sci-Fi” slice of the pie is exploded as
specified in the explode vector (Figure 10.20).
One important factor to remember in a pie chart is the missing slice.14
When the sum of all the elements in a vector is less than 1(sum < 1) and
such vector is given as an input vector to the pie() function, in such cases, the
Octave would not calculate the percentage proportion for each slice; it will
use the vector elements itself to proportionate the data, leaving a missing
slice for the part of the data that is undefined.7,15
Octave:3>

pie ([0.17,0.61,0.2], {"Coffee", "Tea", "Milk"});


title ("Pie Chart for Beverage Preferences")
Color13:
In the above example, you can see that the input vector contains three
elements – 0.17, 0.61, and 0.2. The sum of these elements is 0.98 (0.98 < 1). So
here, Octave does not calculate the sum and the respective percentages and
considers the elements to be taken in percentages and keeps a missing slice
at the last (Figure 10.21).
Scatter Plot
In GNU Octave, a scatter plot is created using the scatter() function. The
syntax of the scatter() function is given as the following:
Syntax: scatter (x, y, s, c, style, “filled”)1

“label_plot”: Note that label_plot is the name given to the plot legend. Also,
the semicolons used in the syntax of the plot legend are mandatory.
Pie Charts
Pie charts are often used to show the data proportions in the data, i.e, the
contribution of a particular category in a set of data. In GNU Octave, a pie chart
is created using the pie function. The syntax of the pie() function is as follows:
Syntax: pie(x, explode, labels)
Attributes:

• x – x is the vector based on which the pie chart is plotted. Here, the size of
the slice is calculated based on the percentage it contributes to the total data.
• explode – explode is a vector of the same size as that of the input vector x,
and it contains elements as 0(zero) or any nonzero element.7 A nonzero ele-
ment represents that slice of the pie to be exploded. FIGURE 10.20
Pie chart example.
• labels – The label cell array represents the label to each slice.
GNU Octave as a Data Science Tool 245 246 Fundamentals of Data Science

Attributes: Octave:
• x, y – x and y are the vectors that are used to plot the markers.
4>1x = randn (100, 1);
• s – s is the marker size. It is computed as sqrt(s). The default value of s is 36 y = randn (100, 1);
sq. points.12 scatter (x, y, "m", "d", "filled");
• c – c represents the color of the marker. The notations for the different colors title ("Scatter() Plot");
are mentioned above in the format arguments.
Histogram
• style – style represents the shape of the marker. The notation for various Now, let’s see how to build a histogram in GNU Octave.
styles of the marker is covered in the format arguments. In GNU Octave, the histogram is created using the hist() function.
• “filled” – If this attribute is specified, the marker will be filled or else it will The hist() function mainly needs one input which is the Y-values vector.
be a hollow marker (Figure 10.22). Other property parameters can be included or excluded as per the require-
ments of the user. If the number of bins to be considered is not specified by
the user, by default, Octave generates ten bins (Figure 10.23).
Let’s create a histogram.
Octave:

5>1A = hist (randn (10000, 1), 30);


xlabel ("Value");
ylabel ("Count");
title ("Histogram");

Now, as you can see in the above source code, we have generated a vector
of 10,000 random numbers and provided it to the hist() function to create a
histogram along with 30 bins.

FIGURE 10.21
Example of the pie chart missing slice.

FIGURE 10.22 FIGURE 10.23


Scatter plot. Histogram example.
GNU Octave as a Data Science Tool 247

FIGURE 10.24
Storing the number of elements in the bins.

If you observe the source code, the hist() function is assigned to array A.
This is carried out to store the number of elements in every bin. As we had
given the input to create 30 bins, in the above figure, you can see that the
array consists of 30 elements, and each element represents the number of
items stored in that particular bins. The addition of these elements will sum
up to 10,000 as we had generated 10,000 random numbers to create the histo-
gram (Figure 10.24).

10.5 Summary
GNU Octave is profoundly used for numerical computations as numerical
computations and vector/matrices go hand in hand. We first studied vari-
ous techniques to create a vector and extract the elements of the vector.1 We
also looked at a few built-in functions to create vectors. We then moved on
to study many ways to create matrices and built-in functions to manipulate
it. GNU Octave provides multiple built-in functions for arithmetic opera-
tions. These arithmetic operations are highly beneficial as they ease out the
process and cut down the lines of code to just a single-line function. GNU
Octave also provides functions to perform set operations such as the union
and intersection of sets. To wrap-up the chapter, we went through some
plotting techniques provided by GNU Octave and its different formatting
arguments.

Exercise

You might also like