0% found this document useful (0 votes)
8 views17 pages

Matlab - Tutor4 - Logic

Uploaded by

Gemini Goel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views17 pages

Matlab - Tutor4 - Logic

Uploaded by

Gemini Goel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Formatting Text

Data is saved in the form of arrays. When we display the data, it comes in
the form of an array, and that may not be as representable as always. So,
there are some formatting operators available in the MATLAB to convert the
data to text and format the output as per our requirements.

o Formatting operators control notation, alignment, significant digits of


the output.
o We can combine formatting operators with normal text and special
characters in a format specifier.
o Formatting operators can be used with the functions: compose,
num2str, sprintf, fprintf, assert, error, warning, and MException.

Example:

1. >> % create a row vector using rand function


2. >> r = rand(1,3);
3. >> % combining normal text, special character, formatting operator in the o
utput
4. >> t = sprintf('Displaying 3 random numbers: \n 1)%f \n 2)%.2f \n 3)%12f',r);

Output:

>> t

t =
'Displaying 3 random numbers:
1)0.957167
2)0.49
3)0.800280'

Fields of the Formatting Operator in MATLAB


The % percent sign always leads the formatting operator. A formatting
operator can have a maximum of six fields-the conversion character,
subtype, precision, field width, flags, and numeric identifier.

o The conversion character is an only required field among all six fields.
o The conversion character must always lead by a % percent sign.
o And no space character is allowed in between the fields of formatting
operator.

Syntax Example:

PlayNext
Mute

Current Time 0:00

Duration 18:10
Loaded: 2.94%
Â
Fullscreen

Conversion Character
The conversion character is an only required field, and it specifies the
notation of the output. The conversion character is denoted by a single
alphabetical character and appears last in the format specifier.

Sl. No. Conversion character Description

1. c Single character

2. d Decimal notation (signed)

3. e Exponential notation (using a lowercase e, as in 3.141

4. E Exponential notations (using a uppercase E, as in 3.14

5. f Fixed-point notation
6. g The more compact of the %e or %f (insignificant z
print)

7. G Similar to %g, but using an uppercase E

8. o Octal notation (unsigned)

9. s Character vector or string array

10. u Decimal notation (unsigned)

11. x Hexadecimal notation (unsigned, using lowercase lett

12. X Hexadecimal notation (unsigned, using lowercase lett

Example:

1. >>p=100;
2. >>ch = 'cdeEfgGosuxX';
3.
4. >>res = sprintf("%c\t\t%c \n%c\t\t%d \n%c\t\t%e \n%c\t\t%E"+...
5. "\n%c\t\t%f \n%c\t\t%g \n%c\t\t%G \n%c\t\t%o"+...
6. "\n%c\t\t%s\n%c\t\t%u\n%c\t\t%x\n%c\t\t%X?, ...
7. ch(1),p,ch(2),p,+ch(3),p,ch(4),p,ch(5),p,ch(6),+...
8. p,ch(7),p,ch(8),p,ch(9),p,ch(10),p,ch(11),p,ch(12),p);

Output:

>> res
res =

"c d
d 100
e 1.000000e+02
E 1.000000E+02
f 100.000000
g 100
G 100
o 144
s d
u 100
x 64
X 64"

Subtype
The subtype field is represented by a single alphabetic character that comes
immediately before the conversion character. The conversion characters %o,
%u, %x, and %X treat data input as integers, without the subtype field. So,
use one of the following subtype specifiers to treat data input as floating-
point values and convert them to octal, decimal, or hexadecimal
representations.

Subtype
Description
specifier
Treats input data as double-precision floating-point values rather tha
b
integers.
Treats input data as single-precision floating-point values rather tha
t
integers.

Example:

1. >> p = 100;
2.
3. >> res = sprintf('before using subtype:\t%u\nafter using subtype:\t%tu',p,p);

4. </pre>

Output:

>> res

res =

'before using subtype: 100


after using subtype: 1120403456'

Precision
The precision field is denoted by a non-negative integer that immediately
comes after a period (dot). It is used with %f, %e, and %E operators and
indicates the number of digits to display to the right of the decimal point.

Example:

1. >> res = sprintf('output without and with precision field:\t%f\t%.2f\t%e\t


%.2e',pi*30*ones(1,4));

Output:

>> res

res =

'output without and with precision field: 94.247780 94.25 9.424778e+01


9.42e+01'
Field Width
The field width is a non-negative integer and comes with or without decimal
point precision. As the precision field specifies the number of digits after the
decimal point, the field width specifies how many numbers of total
characters should be displayed in the output. If the field width is higher than
the number of characters in the input data, then by default, the output text
is padded with space characters.

Example:

1. >> res = sprintf('output without and with field width:\t|%x|\t|%15x|\t|%f|\t|


%15f|',303.3*ones(1,4));

Output:

>> res
res =
'output without and with field width: |3.033000e+02| | 3.033000e+02| |
303.300000| | 303.300000|'

Flags
The flags field controls the additional formatting of the output. The
characters used for the flags describe mainly the spacing, padding, and text
alignment.

Flags Description
character

Minus sign Left-justify the output


(-)

Plus sign (+) Right-justify the output if the output is a text, and add a leading plus
sign character if it is number

Space Inserts space before the output

Zero (0) Pad the output with zero instead of space

The pound The pound sign flag is a special case as it is somehow different from
sign (#) other flags. It modifies selected numeric conversions as:
o Prints 0, 0x, or 0X prefix for %o, %x, or %X operators.
o Prints decimal point even when precision is 0 for %f, %e, or %E
operators.
o It doesn't remove trailing zeroes or decimal points for %g or %G
operators.

Example: -Right and left justify:

1. >> sprintf('right-justify:|%+12s|\nleft-justify:|%-12.2f|',"flags",10);

Output:

>> ans

ans =

'right-justify:| flags|
left-justify:|10.00 |'

Example: - Padding with space and zero:

1. >> b = sprintf('padding with space: |%10.2f|\n padding with zero: |


%010.2f|',20,20);

Output:

>> b

b =

'padding with space: | 20.00|


padding with zero: |0000020.00|'

Example: -Pound Sign:

1. >> a=sprintf('%#.0f',10.00);
ADVERTISEMENT

Output:

>> a

a =

'10.'

Identifiers
The output functions such as sprintf prints the output in the same sequence
as it takes input arguments. So, use the identifier to produce the output in a
custom specified order. Identifiers are the integer values and come
immediately after the % percent sign following by a $ dollar sign.

Default order

Example:

1. >> t1 = sprintf('%s %s %s','1st','2nd','3rd');

Output:

>> t1

t1 =

'1st 2nd 3rd'

Custom order using identifier

Example:

1. >> t2 = sprintf('%3$s %1$s %2$s','1st','2nd','3rd');

Output:

>> t2

t2 =

'3rd 1st 2nd'

Displaying Special Characters in the Output


Special characters are meant to serve particular purposes, so these cannot
be used as ordinary text. To make special characters as part of the output
text, use specific character sequences.

Special character Character sequence

Single quotation mark '' (single quote two times

%%

Backslash \\

Alarm \a
Backspace \b

Form feed \f

New line \n

Carriage return \r

Horizontal tab \t

Vertical tab \v

Representation of Unicode numeric value of the \xN


hexadecimal number, N Example: sprintf('\x6A
character 'j'

Representation of Unicode numeric value of the octal \N


number, N Example: sprintf('\100
character '@'

Rules for setting Field Width and Precision


The formatting operators follow specific rules for formatting the output text.
And field width & precision define how a number should be displayed in the
output. Let's examine with an illustrated example:

o If precision is not specified, then the default value is set to six.


o If precision p is less than the number of a digit in the fractional part of
the input, then only p digits are displayed after the decimal point, and
the output value is rounded off.
o If the precision p is higher than the no. of digits in the fractional part,
then the fractional part is shown with added zeroes to the right of p
digits.
o If the field width w is not specified, then the default value is calculated
as per p+1+n, n is the number of digits in the whole part of an input
value.
o If the field width w is higher than p+1+n, then the whole part of the
output is padded to the left with either space or zero additional
characters, calculated as w-(p+1+n).

Field Width and Precision, Outside the Format Specifier


To specify the field width and precision outside the format specifier, use an
asterisk (*) in place of the field width or precision fields of the formatting
operator. The place of the asterisk should match the place of the number
specifying the fields in the input arguments. Lets' understand with an
example:

Example:

1. >> t3 = sprintf('%*f %.*f %*.*f',10,123.456,3,10.2345,4,2,pi);

Output:

>> t3

t3 =

?123.456000 10.235 3.14?

Explanation of the above example:

Formatting Operator Description

%*f Specify field width as the following input argument, 10.

%.*f Specify precision as the next input argument, 3.

%*.*f Specify width and precision as the next input arguments, 4, a

Specifying Identifiers in place of Field Width and Precision


We can specify numbered identifiers for field width and precision, and the
value for the identifier comes from input arguments.

Example:

1. >> t4 = sprintf('%1$*4$f %2$.*5$f %3$*6$.*7$f',123.456, 12.36587, 3.145


678, 10, 4, 4, 2);

Output:

>>t4 =

'123.456000 12.3659 3.14'

Lets' examine the above example:

Formatting operator Description

%1$*4$f 1$ specifies the first input argument, 123.456, as


*4$ specifies the fourth input argument, 10, as the field widt

%2$.*5$f 2$ specifies the second input argument, 12.36587, as


.*5$ specifies the fifth input argument, 4, as the precision

%3$*6$.*7$f 3$ specifies the third input argument, 3.145678, as


*6$ specifies the sixth input argument, 4, as the fi
.*7$ specifies the seventh input argument, 2, as the precisio

MATLAB if...end statement


ADVERTISEMENT
ADVERTISEMENT

o The if is a conditional statement that provides the functionality to


choose a block of code to execute at run time.
o A predefined condition is checked, and the remaining code executes
based on the output of the condition.
o The if statement is defined by the if
o The control flows within the if block if the condition is found true.
o Always close the if block with the end
o The elseif and else are optional, use them if there are more
conditions to be checked.
o The elseif and else are an optional parts of the if statement and don't
require additional end
o Remember not to use space in between else & if of the elseif keyword,
because this leads to nested if statement and each if block needs to
be close with the end
o There is no limit to use multiple elseif
o We can nest the if statement by using it within another if

Syntax:

1. if expression
2. Statements
3. end

Flow Diagram of If...end Statement


Example

1. % program to announce bonus on max hour of job


2. a = randi(250,12,2)
3. pr = 0;
4. bonus = 10000;
5. for k = 1:numel(a)
6. pr = pr + a(k);
7. end
8. disp(['total hours of job done by you in a year are: ',num2str(pr)])
9. if pr >= 2800
10. disp(['Great...you earned a bonus amount of Rs. ',num2str(bonus)])
11. else
12. disp(['better luck next year....'])
13. end

Output:

a = 12×2
227 183
134 177
28 196
207 72
85 174
74 140
187 100
3 16
13 196
167 85
total hours of job done by you in a year are: 3085
Great...you earned a bonus amount of Rs. 10000

MATLAB if-else... end statement


If the first condition is not true, then we can define other statements to run
by using the else keyword.

Syntax:

1. if expression
2. Statements
3. else
4. Statements
5. end

Flow Diagram of if...else...end Statement


Example1:

1. % program to check the number is even or odd


2. a = randi(100,1);
3. if rem(a,2) == 0
4. disp('an even number')
5. else
6. disp('an odd number')
7. end

Output:

a = 15
an odd number

Example2:
Using if-else statement to determine the largest of two number

1. num1 = input('Enter number 1: ');


2. num2 = input('Enter number 2: ');
3. if (num1 > num2)
4. disp('num1 is greater than num2')
5. else if (num1 < num2)
6. disp('num1 is less than num2')
7. else if (num1 == num2)
8. disp('num1 is equal to num2')
9.
10. end

Output:

PauseNext
Mute

Current Time 0:00

Duration 18:10
Loaded: 2.94%
Â
Fullscreen
Enter number 1: 15
Enter number 2:20
num1 is less than num2

MATLAB if-elseif-else...end statement


If we have more than one option or condition to check, then
use elseif keyword.

Syntax:

1. if expression
2. Statements
3. elseif expression
4. Statements
5. else
6. Statements
7. end
Example1:

1. % program to compare two numbers


2. % generate random number for your age
3. n = randi(100,1);
4. age = 23;
5. % check the number is greater than your age
6. if n > age
7. disp('i am younger')
8. elseif n < age
9. disp('you are younger')
10. else
11. disp('we are of same age')
12. end

Output:

n = 9
you are younger

You might also like