0% found this document useful (0 votes)
21 views

Chapter#5

The document discusses programming in MATLAB. It covers topics like program structure, variables, operators, conditional statements, loops and functions. Key points include that a MATLAB program is a sequence of commands, commands can be executed conditionally using if/else statements, and loops like for and while loops can repeat commands. Functions allow breaking programs into reusable parts.

Uploaded by

kawibep229
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Chapter#5

The document discusses programming in MATLAB. It covers topics like program structure, variables, operators, conditional statements, loops and functions. Key points include that a MATLAB program is a sequence of commands, commands can be executed conditionally using if/else statements, and loops like for and while loops can repeat commands. Functions allow breaking programs into reusable parts.

Uploaded by

kawibep229
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Programming in

MATLAB
 A computer program is a sequence of computer commands.
 In a simple program the commands are executed one after the other in the order they are typed
but in many situations, commands are not necessarily executed in the order they are typed.
 In other situations there might be a need to repeat a sequence of commands several times
within a program.
RELATIONAL AND LOGICAL OPERATORS

 A relational operator compares two numbers by determining whether a comparison statement


(e.g., 5 < 8) is true or false. If the statement is true, it is assigned a value of 1. If the statement
is false, it is assigned a value of 0.

Relational operator Description


< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
~= Not Equal to
Some examples are:
Some examples are:
Some examples are:
Some examples are:
Logical operators: Logical operators have numbers as operands. A nonzero
number is true, and a zero number is false.
Some examples are:
Using Script Files
 A script file is a sequence of MATLAB commands, also called a program.
 When a script file runs (is executed), MATLAB executes the commands in the order they are
written just as if they were typed in the Command Window.
 When a script file has a command that generates an output (e.g., assignment of a value to a
variable without a semicolon at the end), the output is displayed in the Command Window.
 Using a script file is convenient because it can be edited (corrected or otherwise changed) and
executed many times.
 Script files can be typed and edited in any text editor and then pasted into the MATLAB editor.
 Script files are also called M-files because the extension .m is used when they are saved.
INPUT TO A SCRIPT FILE
 The variable is defined and assigned a value in the script file
 The variable is defined and assigned a value in the Command Window
 The variable is defined in the script file, but a specific value is entered in the Command Window
when the script file is executed.
In this case the variable is defined in the script file, and when the file is executed, the user is prompted to
assign a value to the variable in the Command Window.
This is done by using the input command for creating the variable.
The input command can also be used to assign a string to a variable

 where the ‘s’ inside the command defines the characters that will be entered as a string. In this
case when the prompt message appears, the text is typed in without the single quotes, but it is
assigned to the variable as a string.

example: script file


A=input('Enter first number: ');
B=input('Enter second number: ');
C=A+B
OUTPUT COMMANDS
 MATLAB has several commands that can be used to generate displays. The displays can be
messages that provide information, numerical data, and plots. Two commands that are
frequently used to generate output are disp and fprintf.
The disp Command:
 The disp command is used to display the elements of a variable without displaying the name of
the variable, and to display text.
example:
The fprintf Command
 The fprintf command can be used to display output (text and data) on the screen
 With this command (unlike with the disp command) the output can be formatted.
 For example, text and numerical values of variables can be intermixed and displayed in the same line.
Using the fprintf command to display text:

Using the fprintf command to display a mix of text and numerical data:
Examples:
Refer help window and text book for formatting fprintf
 Conversion specifications
 Escape characters
CONDITIONAL
STATEMENTS
 A conditional statement is a command that allows MATLAB to make a decision of whether
to execute a group of commands that follow the conditional statement, or to skip these
commands.
 In a conditional statement expression .
If the expression is true, a group of commands that follow the statement are
executed.
If the expression is false, the computer skips the group.

 The basic form of a conditional statement is:


The if-end Structure
 The if statement’s basic form is

if logical expression
Statements
end

 Every if statement must have an accompanying end statement. The end statement marks the
end of the statements that are to be executed if the logical expression is true.
The structure of the if-end conditional statement.
The if-else-end Structure
 The basic structure for the use of the else statement is

if logical expression
statement group 1
else
statement group 2
end
Example
clc;
clear;
x=input('enter the number:' );
if x >=0
y=sqrt(x);
fprintf('Square root of %d is %f\n',x,y);
else
disp('number is negative');
end
The if-elseif-else-end Structure

The general form of the if statement is


if logical expression 1
statement group 1
elseif logical expression 2
statement group 2
else
statement group 3
end
The else and elseif statements may be omitted if not required.
However, if both are used, the else statement must come after the
elseif statement to take care of all conditions that might be
unaccounted for.
The structure of the if-elseif-else-end conditional statement.
Example
clc;
clear;
x=input('enter a no: ');
if (x>0 && x<=6)
y=x.^2;
fprintf('Power of Number is %d \n',y);
elseif (x>=7)
y=sqrt(x);
fprintf('Square root is %f\n',y);
elseif (x<0)
disp('number is negative')
else
disp('Its ZERO');
end
The following statements

if logical expression 1
if logical expression 2
statements
end
end
can be replaced with the more concise program

if logical expression 1& logical expression2


statements
end
Rewrite the following statements to use only
one if statement.

if x<y && z<10


if x < y
w=x*y*z;
if z < 10
end
w = x*y*z
end
end
1) Run the following Matlab codes and discuss the results.

Clear; Clear;
p=input('enter a value'); p=input('enter a value');
if p>5 if p>5
y=1; y=1;
elseif p>10 if p>10
y=2; y=2;
end end
disp(y); end
disp(y);
THE switch-case STATEMENT

 The switch-case statement is another method that can be used to direct the
flow of a program. It provides a means for choosing one group of commands
for execution out of several possible groups.
 The switch structure provides an alternative to using the if, else if and else
commands. Anything programmed using switch can also be programmed
using if structures.
 However, for some applications the switch structure is more readable than
code using the if structure.
The structure of a switch-case statement.
Example
clc;
clear;
m = input('Enter a Month(1-12): ');
switch m
case {1 2 3 4 5}
disp('Spring')
case {6 7}
disp('Summer')
case {8 9 10 11 12}
disp('Fall')
otherwise
disp('Bad Month Index')
end
LOOPS
A loop is another method to alter the flow of a computer program. In a loop, the execution of a
command, or a group of commands, is repeated several times consecutively.

for-end Loops
 In for-end loops the execution of a command, or a group of commands, is
repeated a predetermined number of times.
The structure of a for-end loop.
for k = f : s : t
........ A group of MATLAB
commands.
end
 In the first pass k = f and the computer executes the commands between the
for and end commands.
 Then, the program goes back to the for command for the second pass.
 k obtains a new value equal to k = f + s, and the commands between the for
and end commands are executed with the new value of k.
 The process repeats itself until the last pass, where k = t.
 Then the program does not go back to the for, but continues with the
commands that follow the end command.
A simple example of a for-end loop (in a script file) is:
For k=1 : 3 : 10
x = k^ 2
end
 When this program is executed, the loop is executed four times.
 The value of k in the four passes is k = 1, 4, 7, and 10,
 which means that the values that are assigned to x in the passes are
x = 1, 16, 49, and 100, respectively.
A simple example of a for-end loop, Execute and discuss the working
of for loop
clc;
clear;
x=input('Enter a Number:');
n=5;
for(i=1:n)
y=x+i;
disp(y);
end
clc; clear;
n=input('Enter the number of terms: ' );
S=0; %Setting the sum to zero.
for k=1:n
S=S+(-1)^k*k/2^k; %for-end loop.
end
fprintf('The sum of the series is: %f\n',S)

In each pass one element of the series is calculated and is added to the sum of the
elements from the previous passes.
while-end Loops
 while-end loops are used in situations when looping is needed but the number of passes is not known in
advance.
 In while-end loops the number of passes is not specified when the looping process starts.
 Instead, the looping process continues until a stated condition is satisfied.

The structure of a while-end loop.


 The first line is a while statement that includes a conditional expression.
 When the program reaches this line the conditional expression is checked.
 If it is false (0), MATLAB skips to the end statement and continues with the
program.
 If the conditional expression is true (1), MATLAB executes the group of
commands that follow between the while and end commands.
 Then MATLAB jumps back to the while command and checks the
conditional expression.
 This looping process continues until the conditional expression is false.
Print Your Name n times Using While loop
clc; clear;
x=input('Enter Your name:','s' );
disp(x);
disp(x);
disp(x);
disp(x);
disp(x);
The Above program change to while loop

clc; clear;
n=5;
i=1;
x=input('Enter Your name:','s' );
while(i<=n)
disp(x);
i=i+1;
end
Print numbers, its square and its square roots n times Using While loop.

clc;
clear;
n=input('limit:');
i=1;
fprintf('Number\tSquare\tSquareRoot\n');
while(i<=n)
a=sqrt(i);
b=i^2;
fprintf('%d\t\t%d\t\t%g\n',i,b,a);
i=i+1;
end
clc;clear;
n=input('limit:');
i=1;
fprintf('Number\tSquare&SquareRoot\n');
while(i<=n)
if (rem(i,2)==0)
a=sqrt(i);
fprintf('%d\t\t%g\n',i,a);
i=i+1;
else
a=i^2;
fprintf('%d\t\t%g\n',i,a);
i=i+1;
end
end
NESTED LOOPS AND NESTED CONDITIONAL STATEMENTS
 Loops and conditional statements can be nested within other loops or conditional statements.
 This means that a loop and/or a conditional statement can start (and end) within another loop or conditional
statement.
 There is no limit to the number of loops and conditional statements that can be nested.
 It must be remembered, however, that each if, case, for, and while statement must have a corresponding
end statement.
Structure of nested loops
Example: Creating a matrix with a loop

clc;
clear;
m=input('row:');
n=input('column:');
for i=1:m
for j=1:n
x(i,j)=input('enter elements:');

end
end
disp(x);
THE break AND continue COMMANDS
The break command:
When inside a loop (for or while), the break command terminates the execution of the loop (the
whole loop, not just the last pass).
When the break command appears in a loop, MATLAB jumps to the end command of the loop
and continues with the next command (it does not go back to the for command of that loop).

clc;clear;
for i=1:5
a=input('enter your no: ');
if(a<0) %exit your loop when
any negative no. input
break;

end
fprintf('Number is %d\n',a);
end
The continue command:
The continue command can be used inside a loop (for or while) to stop the present pass and start the next pass
in the looping process.
The continue command is usually a part of a conditional statement.
When MATLAB reaches the continue command, it does not execute the remaining commands in the loop, but
skips to the end command of the loop and then starts a new pass.

clc;clear;
for i=1:5
a=input('enter your no: ');
if(a<0) %exit your loop when any
negative no. input
continue;
end
n=sqrt(a);
fprintf('Square root is %f\n',n);
end

You might also like