0% found this document useful (0 votes)
13 views16 pages

IE142 Week 14

Uploaded by

Sevim Köse
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)
13 views16 pages

IE142 Week 14

Uploaded by

Sevim Köse
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
You are on page 1/ 16

IE142 Computer Programming II

2021–2022 Spring

Week 14 (24.05.2022)

Asst. Prof. Tolga Ulaş Gürbüz │ Asst. Prof. Mehmet Merkepçi


IE142 Computer Programming II Week 14 (24.05.2021)

Revisiting the two previous exercises:


We can optimize the two previously written functions, fun_gcd and fun_primes so that they will run faster.

Some notes on code optimization:

• In computer science, program optimization, code optimization, or software optimization, is the


process of modifying a software system to make some aspect of it work more efficiently or use
fewer resources. In general, a computer program may be optimized so that it executes more
rapidly, or to make it capable of operating with less memory storage or other resources, or draw less
power.

• Although the word "optimization" shares the same root as "optimal", it is rare for the process of
optimization to produce a truly optimal system. A system can generally be made optimal not in
absolute terms, but only with respect to a given quality metric, which may be in contrast with other
possible metrics. As a result, the optimized system will typically only be optimal in one application or
for one audience. One might reduce the amount of time that a program takes to perform some task
at the price of making it consume more memory. In an application where memory space is at a
premium, one might deliberately choose a slower algorithm in order to use less memory. Often there
is no "one size fits all" design which works well in all cases, so engineers make trade-offs to
optimize the attributes of greatest interest.

• Optimization can reduce readability and add code that is used only to improve the performance.
This may complicate programs or systems, making them harder to maintain and debug. As a result,
optimization or performance tuning is often performed at the end of the development stage.
IE142 Computer Programming II Week 12 (10.05.2022)

Exercises
 Write the code for function fun_gcd(A,B) that will output the “greatest
common divisor” of positive integers A and B.
IE142 Computer Programming II Week 12 (10.05.2022)

Exercises
 Write the code for function fun_gcd(A,B) that will output the “greatest
common divisor” of positive integers A and B.
Solution:
1st version: «optimized» version:

function Out = fun_gcd(A,B) function Out = fun_gcd(A,B)


if A>=B if A>=B
min=B;
min=B;
else
else min=A;
min=A; end
end for i=1:min
for i=min:-1:1 if rem(A,min/i)==0 && rem(B,min/i)==0
if rem(A,i)==0 && rem(B,i)==0 Out = min/i;
Out = i; break
end
break
end
end end
end
end For A=40000 and B=18000
it takes 9 steps and 0.001923 seconds.
For A=40000 and B=18000,
it takes 16001 steps and 2.004022 seconds. For A=40000 and B=18000,
it takes 3 steps and 0.000866 seconds.
For A=400000 and B=150000,
it takes 100001 steps and 13.011095 seconds.
IE142 Computer Programming II Week 12 (10.05.2022)

Exercises
 Write the code for function fun_primes(A) that will output an array
containing all prime numbers smaller than or equal to the positive integer A.
IE142 Computer Programming II Week 12 (10.05.2022)

Exercises
 Write the code for function fun_primes(A) that will output an array
containing all prime numbers smaller than or equal to the positive integer A.
Solution:
1st version: «optimized» version:

function Out = fun_primes(A) function Out = fun_primes(A)


k=1; k=1;
for m=2:A
for i=2:A
is_prime = 1;
for j=2:i for n=2:m/2
if(rem(i,j)==0) if(rem(m,n)==0)
break; is_prime = 0;
end break;
end end
if(i == j) if((A/n)<n)
break;
Out(k) = i;
end
k = k +1; end
end if is_prime == 1
end Out(k) = m;
end k = k +1;
end
A = fun_primes(300000); end
Elapsed time is 103.390585 seconds. end

A = fun_primes(300000);
Elapsed time is 1.147309 seconds..
IE142 Computer Programming II Week 14 (24.05.2021)

 READING FROM and WRITING TO TEXT FILES


 There are several lower-level functions for reading from or writing to text files.
 The function fscanf reads formatted data into a matrix, using conversion formats such
as %d for integers, %s for strings, and %f for floats (double values).
 The function fprintf writes data to a text file, using conversion formats such as %d for
integers, %s for strings, and %f for floats (double values).
 The fgetl and fgets functions both read strings from a file one line at a time.
 The textscan function reads text data from a file and stores the data in a cell array; it
also uses conversion formats.
 All of these functions require first opening the file (fopen) and then closing it (fclose)
when finished.
 As the fgetl and fgets functions read one line at a time, these functions are typically inside
some form of a loop.
 The fscanf and textscan functions can read the entire data file into one data structure. The
file must be opened using fopen first, and should be closed using fclose after the data has
been read. However, no loop is required; they will read in the entire file automatically into
a data structure.
 The fscanf reads into a matrix variable columnwise from the file. The format information
includes conversion characters much like those used in the fprintf function. It specifies the
format of every line in the file, which means that the lines must be formatted consistently.
 Another option for reading from a file is to use the textscan function. The textscan
function reads text data from a file and stores the data in column vectors in a cell array.
IE142 Computer Programming II Week 14 (24.05.2021)
The textscan command is frequently used since it is very versatile and requires no loops.
 The textscan function is called, in its simplest form, as
cellarray = textscan(fid, 'format');
 The ‘format’ essentially describes the format of columns in the data file, which will then be read
into column vectors. For example, to read the file ‘subjexp.dat’ we could do the following (again,
for simplicity, omitting the error-check of fopen and fclose):
>> fid = fopen('subjexp.dat');
>> subjdata = textscan(fid,'%f %c');
>> fclose(fid)

 The format string '%f %c' specifies that on each line there is a double value followed by a
space followed by a character. This creates a 1 x 2 cell array variable called subjdata. The
first element in this cell array is a column vector of doubles (the first column from the file);
the second element is a column vector of characters (the second column from the file), as
shown here:
>> subjdata
subjdata =
[5x1 double] [5x1 char]
>> subjdata{1}
ans =
5.3000
2.2000
3.3000
4.4000
1.1000
>> subjdata{2}
ans =  To refer to individual values from the vector, it is necessary to index into the cell array
a using curly braces and then index into the vector using parentheses. For example, to refer
b to the third number in the first element of the cell array:
a
a >> subjdata{1}(3)
ans = 3.3000
b
IE142 Computer Programming II Week 14 (24.05.2021)

 Create a text file using a text editor (e.g., Notepad) in your computer, name it Products.txt,
and enter the following lines into this file as follows:
Products.txt
1001 hammer 2.58
1002 plier 1.20
1003 screwdriver 1.56
1004 soldering iron 3.70
1005 wrench 2.60
 Save the file, write the following Octave code;

f1=fopen('Products.txt');
C = textscan(f1,'%d %s %f');
fclose(f1);

fprintf('catalog# description \t\t cost \n');


fprintf('---------------------------------------\n');
for i=1:length(C{1})
fprintf('%5d \t %-14s \t %6.2f \n', C{1}(i), C{2}{i},C{3}(i));
end

 To get the following output:


catalog# description cost
---------------------------------------
1001 hammer 2.58
1002 plier 1.20
1003 screwdriver 1.56
1004 soldering-iron 3.70
1005 wrench 2.60
IE142 Computer Programming II Week 14 (24.05.2021)

 Suppose now that the file SysDia.txt contains the patients’ names as well as their blood
pressure data, and that we wish to read in and store all of the data, i.e. names and blood
pressures:
Joe Bloggs 51 85
Josephine Bloggs 88 141
Zhang San 67 95
Anders Andersen 77 111
Erika Mustermann 68 115
Ola Nordmann 99 171
Jan Kowalski 80 121

 Since, textscan returns a cell array rather than a normal array, and cell arrays can contain
mixed data types, it is possible to read this data using textscan.
% open file
fid = fopen('SysDia.txt', 'r');
if (fid == −1)
error('File cannot be opened');
end

% read systolic and diastolic blood pressure


data = textscan(fid, '%s %s %d %d');

% close file
fclose(fid);

 The type of the variable data returned by textscan will now be a 1×4 cell array.
 The first and second elements of data are arrays that contain the first names and
second names of the patients respectively. In fact, since the lengths of the strings vary
these first two elements are themselves cell arrays.
a. The third and fourth elements of data are normal arrays of integers representing
the systolic and diastolic blood pressures of the patients. Try entering this code into
an Octave script m-file, running it and inspecting the data variable.
IE142 Computer Programming II Week 14 (24.05.2021)

readtable
Create table from file

Syntax
T = readtable(filename)
T = readtable(filename,Name,Value)
T = readtable(filename,opts)
T = readtable(filename,opts,Name,Value)

Description

T = readtable(filename) creates a table by reading column oriented data from a file.


readtable determines the file format from the file extension:
•.txt, .dat, or .csv for delimited text files
•.xls, .xlsb, .xlsm, .xlsx, .xltm, .xltx, or .ods for spreadsheet files
readtable creates one variable in T for each column in the file and reads variable names from the first row of the file. By default,
the variables created are double when the entire column is numeric, or cell arrays of character vectors when any element in a
column is not numeric.

T = readtable(filename,Name,Value) creates a table from a file with additional options specified by one or more name-value pair
arguments.
For example, you can specify whether readtable reads the first row of the file as variable names or as data.

T = readtable(filename,opts) creates a table using the import options opts.


T = readtable(filename,opts,Name,Value) creates a table using the import options and with additional options specified by one or
more of these name-value pair arguments: ReadVariableNames,ReadRowNames, DateLocale, Encoding, Sheet, and Basic.
IE142 Computer Programming II Week 14 (24.05.2021)

Read Specific Range of Data from Spreadsheet

Create a table using data from a specified region of the spreadsheet patients.xls. Use the data
from the 5-by-3 rectangular region between the corners C2 and E6. Do not use the first row of
this region as variable names.
T = readtable('Ex_Excel_Book1.xlsx', 'Range', 'A2:C4', 'ReadVariableNames',false)
T contains default variable names.

Create Table from Spreadsheet Including Row Names

Create a table from a spreadsheet that contains variable names in the first row and row names
in the first column.
T = readtable('Ex_Excel_Book1.xlsx','ReadRowNames',true);
IE142 Computer Programming II Week 14 (24.05.2021)

 IMAGE FILES
 Color images are represented as matrices, of picture elements called pixels.
 In MATLAB, an image is represented by a matrix in which each element corresponds to a
pixel in the image. Each element that represents a particular pixel stores the color for that
pixel.
 There are two basic ways in which the color can be represented:
 true color or RGB, in which the three color components are stored (red, green, and
blue, in that order) in layers in a three-dimensional matrix,
 index into a colormap, in which the value stored for each pixel is an integer that refers
to a row in another matrix called a colormap; the colormap stores the red, green, and
blue components of colors in three separate columns.
 Thus, for an image that has m n pixels, there are two methods for representing color. In
the true color or RGB method, all of the information is stored in one 3D matrix with the
size m  n 3. The first two indices represent the coordinates of the pixel. The third index
is the color component, so (:,:,1) is the red, (:,:,2) is the green, and (:,:,3) is the blue
component.
 Typically, colormaps use double values in the range from 0 to 1, and RGB matrices use the
type uint8. We will use only RGB matrices here.
IE142 Computer Programming II Week 14 (24.05.2021)

 In an 8-bit RGB image, each element in the matrix is of the type uint8, which is an unsigned
integer type storing values in the range from 0 to 255.
 The minimum value, 0, represents the darkest hue available, so all 0s result in a black
pixel. The maximum value, 255, represents the brightest hue.
 For example, if the values for a given pixel coordinates px and py are: (px,py,1) is 255,
(px, py,2) is 0, and (px,py,3) is 0, then that pixel will be bright red.
 All 255s result in a white pixel.
 Images that are stored in various formats, such as JPEG, TIFF, PNG, GIF, and BMP, can be
manipulated in Octave. Built-in functions, such as imread and imwrite, read from and write
to various image file formats. Some images are stored as unsigned 8-bit data (uint8), some
as unsigned 16-bit (uint16), and some are stored as double.
 For example, the following reads a JPEG image into a 3D matrix; it can be seen from the
size and class functions that this was stored as a uint8 RGB matrix.
>> img = imread('a.jpg') ;
>> size(img)
ans =
467 350 3
>> class(img)
ans = uint8

 The image is stored as a true color matrix and has 467350 pixels. The image function
displays the matrix as an image, as shown in.
>> img = imread('a.jpg') ;
>> size(img)
ans =
467 350 3
>> class(img)
ans = uint8
>> class(img)
IE142 Computer Programming II
ans = uint8
Week 14 (24.05.2021)
 The image is stored as a true color matrix and has 467350 pixels. The image function
displays the matrix as an image.

img1 = imread('a.jpg');
img2 = img1 ; img2(:,:,1) = 0 ;
img3 = img1 ; img3(:,:,2) = 0 ;
img4 = img1 ; img4(:,:,3) = 0 ;

subplot(2,2,1), imshow(uint8(img1));
subplot(2,2,2), imshow(uint8(img2)); % only the R component is set to zero
subplot(2,2,3), imshow(uint8(img3)); % only the G component is set to zero
subplot(2,2,4), imshow(uint8(img4)); % only the B component is set to zero
IE142 Computer Programming II Week 14 (24.05.2021)

This is the end of this week’s notes.


Please do not forget to wash your hands frequently
and maintain the social distance.

You might also like