Exp 2
Exp 2
Displaying Information
disp
The disp command displays text or variables in the command window.
Example:
1 disp ( ’ Hello , MATLAB ! ’) ;
fprintf
The fprintf command provides a formatted display of text or variables.
Example:
1 name = ’ John ’;
2 age = 25;
3 fprintf ( ’ Name : % s \ nAge : % d \ n ’ , name , age ) ;
1
clc
The clc command clears the command window.
Example:
1 clc ;
whos
The whos command provides a detailed list of all variables in the workspace,
including their sizes and data types.
Example:
1 x = 10;
2 y = [1 , 2 , 3];
3 name = ’ John Doe ’;
4 whos ;
Formatting Output
format
The format command controls the display format of numeric values. Various
options include:
2
• format long e: Displays numbers in long scientific notation with 15
decimal places.
Conditional Statements
if, else, elseif
Conditional statements allow decision-making based on conditions.
Example:
1 x = 10;
2 if x > 0
3 disp ( ’x is positive ’) ;
4 elseif x < 0
5 disp ( ’x is negative ’) ;
6 else
7 disp ( ’x is zero ’) ;
8 end
Loop Structures
for
The for loop executes a series of statements a specific number of times.
Example:
1 for i = 1:5
2 disp ( i ) ;
3 end
3
while
The while loop executes as long as a condition is true.
Example:
1 i = 1;
2 while i <= 5
3 disp ( i ) ;
4 i = i + 1;
5 end
Comments
Single-line Comments
Use the % symbol to denote single-line comments.
Example:
1 % This is a single - line comment in MATLAB .
2 x = 10; % This assigns the value 10 to the variable x .
Multi-line Comments
Use %{ and %} to enclose multi-line comments.
Example:
1 %{
2 This is a multi - line comment in MATLAB .
3 It can span multiple lines .
4 x = 10;
5 y = 20;
6 %}
4
Example: Script with if-else Statement
Script Name: ifElseScript.m
1 x = 10;
2 if x > 0
3 disp ( ’x is positive ’) ;
4 elseif x < 0
5 disp ( ’x is negative ’) ;
6 else
7 disp ( ’x is zero ’) ;
8 end