Lab # 3
OBJECTIVES OF THE LAB
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
In this lab, we will get an understanding of the following topics:
Making Functions
Control Structures
Relational Constructs
Logical Constructs
Branching Constructs
Looping constructs
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
MAKING FUNCTIONS
A function can be created by the following syntax:
function [output1,output2,...] = function_name(input1,input2,...)
A function is a reusable piece of code that can be called from program to accomplish some specified functionality. A function takes some input arguments and returns some output. To create a function that adds two numbers and stores the result in a third variable, type in it the following code:
function add x = 3;
y = 5;
z = x + y
Save the file by the name of add (in work folder, which is chosen by default), go back to the command window and write
>> add
z =
8
You see that the sum z is displayed in the command window. Now go back to the editor/debugger and modify the program as follows
function addv(x,y) z = x + y
Save the above program with a new name addv, go back to the command window and type the following:
>> addv(3, 5)
z =
8
>> addv(5, 5)
z = 10
We have actually created a function of our own and called it in the main program and gave values to the variables (x, y).
Now go back to the editor/debugger and modify the program as follows
function adv(x, y)
%
% This function takes two values as input,
% finds its sum, & displays the result.
% inputs: x & y
% output: z
% Example: addv(3,6)
% Result: z=9
% z = x + y
Save the program with the same name addv, go back to command window, type the following >> help addv
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ This function takes two values as input, finds its sum, & displays the result. inputs: x & y
output: z
Example: addv(3, 6) Result: z=9
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
Dostları ilə paylaş: |