Lab 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Laboratory Exercise 5

Problem Solving and Functions

I. Introduction

PROBLEM SOLVING

As engineers, we are expected to solve problems based on what we learned. This is


an application of the theories we gathered from the moment that we started to learn.
For every problem, there’s a solution – that’s what we are taught. This solution varies
for every engineer, because it’s not all the time that there will only be one solution and
there’s definitely a lot of ways to solve a specific problem, depending on its nature.

In this chapter, we will learn the advantages of having a computer to solve engineering
problems. In problem analysis, there are three elements that we need, the definition or
model of the problem, the input and the output specifications. To solve such problem,
an algorithm design is needed. For which, the tools and flowchart will be needed. Lastly,
the computer solution a working source code is needed using a programming
language, and our case, the GNU Octave.

Figure 5.1 below shows the cycle at which an engineer usually sees a problem. This is
the problem analysis cycle for solving problems using a programming language. When
the problem is identified, the algorithm is then formulated and its corresponding
flowchart. From this, a machine-readable code will be written based on the flowchart
created. A solution is then finally made. However, as an engineer, our inquisitive minds
never fail to see the problem in a wider perspective after finding a solution. This will
then lead for us to see more interesting problems that needs specific solutions. This
makes the problem analysis process a cycle. Yes, it may be tedious for an engineer,
but that is our nature, because we are problem solvers.

Problem

Solution Algorithm

Code Flowchart

Figure 5.1. Problem Analysis Cycle

As an example, let as take the following problem. This is the classic area of the
triangle problem as shown in Figure 5.2. Here the following can be defined:

Figure 5.2. Area of the Triangle Problem


P a g e 36 | 70
• Problem definition - to find the area of triangle
• Input specification - b and h
• Output specification - variable: area
• Flowchart - shown in Figure 5.3
• Source code - GNU Octave syntax

Figure 5.3. The flowchart for Finding the Area of Triangle

By writing the following code, one can easily solve the problem at hand.

b=input('Input b:');
h=input('Input h:');
Area=0.5*b*h

This code can be easily identified if you have correctly identified the parts of the
previously presented flowchat. But what should be the parts of a flowchart? These are
listed below:

Figure 5.4. List of Flowchat Elements.

Another example will utilize the previously learned for statement. In this case, the
following array should be displayed:

X = [1, 2, 4, 8, 16, 32]

P a g e 37 | 70
Given the sequence, you can identify that it has 2 as a base and the first element has
an exponent of 0 and last having 5.

The following flowchart can then be formulated:

start

stop

Figure 5.5. Flowchart for the Geometric Progression

The following code can then be written.


X=[]; a=2; n=5;
for k=0:n
X=[X a^k];
end
disp(X)

FUNCTIONS

You can create a user-defined function to save time in performing routine process. This
is different from the built-in functions where it does a non-editable function. Here, the
user-defined function can be edited by the user to make it execute the desired function
or process. Having a user-defined function will greatly lessen the number of lines in
your code, which is a good thing. Its pattern is as follows:

function[output_variables]=function_name(input_variables)

See the example in Time to Act: Functions to have an overview on how functions
work.

Additionally, there are specific functions that performs special processes like reading
and writing from an external Ms Excel file or .txt file. For the MsExcel file, GNU Octave
can read it using xlsread function and using xlswrite lets you write or edit values
in the MsExcel file. For the text file, the fopen and fclose functions can be used. You
can also study on the fread and fwrite functions also for further readings and
practice.

Functions for spreadsheet style I/O (.xls .xlsx .sxc .ods .dbf .wk1 etc.) are provided in
the io package. See <https://octave.sourceforge.io/io/>.
P a g e 38 | 70
However, in this manual, since most of these functions vary as the files like MsExcel
updates its file extensions (e.g. xls to xlsx) and for better compatibility, we will be using
only .txt files and .csv files. Text files can be easily made in the note pad and it has a
wide compatibility. For .csv files, the MsExcel files can be easily converted to .csv files
by saving it as .csv or exporting it as .csv. Feel free to test and practice other importing
data functions as you go through the laboratory exercises.

II. Objectives
At the end of the activity, the students are expected to:
1. Analyze various problems relative to power systems;
2. Create an algorithm to solve problems;
3. Use GNU Octave as a programming language to solve problems;
4. Formulate a function script; and
5. Demonstrate opening and accessing data from MsExcel and text files.

III. Materials/Equipment
Computer with a full version of GNU Octave installed

IV. Procedure

TIME TO ACT Problem Solving

1. Start the GNU Octave as instructed at the start of Laboratory Exercise 1 Part IV.
2. Create an m-file and write the following code:
X=input(‘Enter X: ‘);
if X<0
disp(‘negative’)
elseif X==0
disp(‘zero’)
else
disp(‘positive’)
end

Tip: The previous code uses an input function which makes


your script more user-interactive. This can be used if you
want the user to input certain values and you can use such
input in your code. The variable on the left side of the equal
sign will contain the said input value. Be specific as possible
for you to get the exact input that you need for your script.

3. Save the file and execute it.


4. Write the resulting value in the space provided in Part V.1.
5. Execute the file again and input another value and see the results. Record it in
Part V.2.
6. Now try run the file again and try having an input that is not a numeric value, say
a letter in the alphabet. See the results and record it in Part V.3.
7. In the last case, you will see an error. The good thing about GNU Octave is that it
points exactly where the error in the code is. This error is caused by the character
(data type char) that was entered in the Variable X. GNU Octave read this as
an additional variable which is undefined.
8. To avoid such, you can add codes to “limit” the input to a desired format. Say
adding another IF statement to limit that the input should be numerical.
9. Retype this improved code in your file:

P a g e 39 | 70
clc;clear;

X=input('Enter X: ','s'); %store the input into a string


Y=str2double(X); %change string to double Y
Check=isnan(Y); %Check if it is not numeric

while Check==1 %while loop to input again


fprintf('Please enter a numeric value:\n')
X=input('Enter X: ','s');
Y=str2double(X);
Check=isnan(Y);
endwhile

X=Y; %store Y data to X


if X<0;
disp('Negative')
elseif X==0;
disp('Zero')
else X>0;
disp('Positive')
end

Tip: In the sample codes, clc and clear commands are always
present to ensure that the previous data and lines are deleted
before running the code. The % when included in line starts a
comment line, it is ignored by the machine and displayed in
green. Use this to explain or have some markers.

10. Execute the file again and try letters and see the results. Record it in Part V.4.

TIME TO ACT Functions

1. Create a new file in the editor window and write the following code:

function [F] = CtoF(C)


% This is function to convert degree Celsius to Fahrenheit.
F=1.8*C+32;

2. Save the file as CtoFfile.m


3. By doing this you are creating a function script.
4. Then, practice the following commands in the command window and record its
responses in Part V.5.

CtoF(0)<enter>
X=CtoF(37)<enter>
y=CtoF(X)<enter>
y=CtoF(100)<enter>
help CtoF<enter>

P a g e 40 | 70
TIME TO ACT Open and Access CSV and Text Files

1. First the create a text file containing the following data:


123
456
789

2. Save it as sample.txt in the current directory.


3. Create a CSV file using MsExcel or any spreadsheet software available with the
following data:

4. As you can notice, this is a typical network data set for a 4-bus power system.
Save this file as sample_data_set.csv. Note: Make sure to save this file in the
current directory, this may be used in future laboratory exercises.

5. In GNU Octave, create a new file in the editor window and write the following
code:

clear;clc;
Z=importdata('sample.txt')
Y=importdata('sample_line_data.csv')
X= csvread('sample_line_data.csv')

6. Save and execute the script and observe its output in the command window and
workspace window. Record the responses in Part V.5.
7. When finished, close Octave and log off and shut down the computer.

P a g e 41 | 70
V. Observation Matrix

Instructions: Put your observations and calculated values in the space provided
1.
Problem Solving

2.
Problem Solving

3.
Problem Solving

4.
Problem Solving

5.
Functions
CtoF(0)<enter>
X=CtoF(37)<enter>
y=CtoF(X)<enter>
y=CtoF(100)<enter>
6.
Open and Access CSV and Text Files

P a g e 42 | 70
VI. Guide Questions
In this part, please provide your answers to the guide questions in the space provided.

1. In the previous example (for statement to display X = [1, 2, 4, 8, 16, 32]), rewrite
the code using while statement.

2. On the example on Part IV. Problem Solving, write the corresponding


flowchart for the IF statement.

3. Why do you think functions can shorten your main script or code?

P a g e 43 | 70
PRACTICE PROBLEMS
In this part, you are encouraged to solve the following problems at home.
You are not required to submit the code and responses of these problems
but it is especially designed to prepare you for the succeeding activities.
Read, practice and enjoy learning GNU Octave. Good luck!

1. Create the shortest m-file to solve for X, Y and Z. Use only functions
or operators appeared in this note.
3X + 4Y + 5Z = 49
4X + 7Y + 3Z = 51
5X + 6Y + nZ= 61
where n is input variable

2. Write the flowchart and create the shortest m-file to count the number of elements in
matrix C that have the magnitude above an input: n( 1+ 1j)

3. Create the shortest m-file to establish the below matrix:

4. Start writing m-file with below syntax.


A=[ 5 2 15 68 23 9 13 50 10]

Write the flowchart and create the shortest m-file to sort the elements in A in ascending
order. DO NOT use the sort(), max(), min() function provided by GNU Octave.

5. Create the shortest m-file to convert the input value of degree Celsius to Fahrenheit and
vice versa. The input format would be “input:##F” or “input:##C” and the program should
return the converted degree depends on the last alphabet.

P a g e 44 | 70

You might also like