0% found this document useful (0 votes)
4 views7 pages

Lecture 2

This lecture focuses on effectively using MATLAB for scientific computing, emphasizing the structure of programming and the MATLAB environment. Students will learn to navigate the interface, control output, and solve equations using both symbolic and numerical methods. Key topics include programming steps, output formatting commands, and solving linear and quadratic equations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views7 pages

Lecture 2

This lecture focuses on effectively using MATLAB for scientific computing, emphasizing the structure of programming and the MATLAB environment. Students will learn to navigate the interface, control output, and solve equations using both symbolic and numerical methods. Key topics include programming steps, output formatting commands, and solving linear and quadratic equations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MAT 242: Computing

Lecture 2 — Working in MATLAB: Environment, Output, and


Equation Solving

1 Purpose of This Lecture


In the previous lecture, MATLAB was introduced as a tool for scientific computing. In this
lecture, we focus on how to work properly in MATLAB. The goal is not only to learn commands,
but to understand how MATLAB is organised, how it communicates results to the user, and
how it should be used to solve mathematical problems correctly and efficiently.
By the end of this lecture, students should be comfortable navigating the MATLAB environ-
ment, controlling output, and solving equations using both symbolic and numerical approaches.

2 Programming (5 Steps)
Before writing any MATLAB code, it is essential to understand how computational problems
are approached. Programming is not about typing commands at random; it is a structured
process of problem solving.
Almost all programs follow the same five conceptual steps.

1. Problem Specification
Identify what the problem is asking, the given inputs, and the required outputs.

2. Algorithm Design
Outline the logical steps needed to solve the problem before writing code.

3. Implementation (Coding)
Translate the algorithm into MATLAB commands using correct syntax.

4. Testing and Debugging


Run the code, check for errors, and verify that the output is reasonable.

5. Documentation and Interpretation


Comment on the code clearly and explain the results in terms of the original problem.

3 The MATLAB Desktop Environment


When MATLAB is opened in its default layout, the interface is divided into several key com-
ponents.

1
Dr. T. Diphofu University of Botswana

3.1 Menu Tabs (Toolstrip)


The Menu Tabs organise MATLAB functionality into logical groups:

• Home: file operations and workspace management

• Plots: visualisation tools

• Apps: interactive MATLAB applications

• Editor: writing and debugging scripts and functions

3.2 Command Window


The Command Window is where commands are entered and executed.
>> 2 + 3
ans =
5

3.3 Command History


The Command History records previously executed commands for reuse.

3.4 Workspace
The Workspace displays all variables currently stored in memory.
>> x = 1:5;

3.5 Current Folder


The Current Folder shows files MATLAB can access directly.

4 Getting Help in MATLAB


MATLAB provides built-in help tools:

• help

• help function name

• Tab completion

5 Getting Help in MATLAB


MATLAB includes an extensive help system that should be used regularly. The help command
provides brief descriptions of functions and their syntax, while more detailed documentation
can be accessed through MATLAB’s built-in help browser. Tab completion assists users by
completing command and variable names as they are typed.
Developing the habit of consulting MATLAB help is an important part of becoming an
independent user.

2
Dr. T. Diphofu University of Botswana

6 Controlling Output in MATLAB


6.1 The format Command
Formatting affects display only and does not change stored values
>> format short % displays up to 4 decimal places
>> pi
ans =
3.1416

>> format long % displays up to 14 decimal places


>> pi
ans =
3.14 159265 35897 93

Scientific notation:
>> format short e % displays in scientific notation up to 4 decimal
places
>> pi
ans =
3.1416 e +00

>> format long e % displays in scientific notation up to 4 decimal


places
>> pi
ans =
3.14 15926 535897 93 e +00

Other formats:
>> format rat % displays rational numbers or approximation in rational
numbers
>> pi
ans =
355/113

>> format bank % displays up to 2 decimal places


>> 12/7
ans =
1.71

6.2 The disp Command


By default, MATLAB displays results in a standard numerical format. However, it is often nec-
essary to control how results are displayed, especially in scientific and engineering applications.
The disp command displays values or messages without printing the variable name.

6.2.1 Displaying Output Using disp


The disp command in MATLAB is used to display the value of a variable or a message
in the Command Window without printing the variable name. This produces cleaner and
more readable output than typing the variable name directly, which prefixes the output with
variable name =.

3
Dr. T. Diphofu University of Botswana

Displaying Numeric Values


Consider the numeric vector
A = [15 150].
Using disp, MATLAB displays only the contents of the variable.
A = [15 150];
disp ( A )

MATLAB output:
15 150

This form of output is preferred when presenting numerical results, as it removes unnecessary
variable labels and focuses attention on the values themselves.

Displaying Text
The disp command can also be used to display text. Text may be written using either character
arrays (single quotes) or string objects (double quotes).
>> disp ( ’ Hello World . ’)

Hello World .

>> disp (" Hello World .")

Hello World .

Both commands produce identical output. The single-quote syntax represents character
arrays, while the double-quote syntax represents MATLAB’s newer string data type.

When to Use disp


The disp command is most suitable when:

• displaying simple numerical results,

• printing short messages to the user,

• output formatting is not critical.

When precise control over numerical precision, alignment, or layout is required, formatted
output using fprintf should be used instead.

6.2.2 Displaying Multiple Variables on the Same Line


Method 1: Concatenation with disp
>> name = ’ Alice ’;
>> age = 12;
>> X = [ name , ’ will be ’ , num2str ( age ) , ’ this year . ’ ];
>> disp ( X )
Alice will be 12 this year .

Method 2: sprintf with disp


X = sprintf ( ’% s will be % d this year . ’ , name , age ) ;
disp ( X )
Alice will be 12 this year .

4
Dr. T. Diphofu University of Botswana

Method 3: Direct fprintf


fprintf ( ’% s will be % d this year .\ n ’ , name , age ) ;
Alice will be 12 this year .

6.3 The fprintf and sprintf Commands


Common format specifiers:
• %s string (text)
• %d integer
• %f fixed-point decimal
• %g compact format

Understanding the Difference Between fprintf and sprintf


Although fprintf and sprintf use the same format specifiers, they behave differently.
The fprintf command prints formatted output directly to the Command Window. This is
why the sentence appears immediately after the command is executed.
>> name = ’ Alice ’;
>> age = 12;
>> fprintf ( ’% s will be % d this year .\ n ’ , name , age )
>> Alice will be 12 this year .

When using fprintf, MATLAB does not automatically move to a new line after printing
output. The line feed character \n must be included explicitly to indicate the end of a line.

In contrast, the sprintf command does not display anything. Instead, it creates formatted
text and stores it in a variable. If the result is not assigned to a variable, MATLAB stores it in
ans.
>> sprintf ( ’% s will be % d this year . ’ , name , age ) % without suppressing
output
ans =
’ Alice will be 12 this year . ’

>> sprintf ( ’% s will be % d this year . ’ , name , age )


ans =
’ Alice will be 12 this year . ’

This explains why nothing appeared immediately in the Command Window when sprintf
was used without disp (but with suppression). The following table shows what happens when
sprintf and fprintf are used with and without suppressing (;).
>> fprintf ( ’% s will be % d this year .\ n ’ , name , age ) ;
Alice will be 12 this year .
>> fprintf ( ’% s will be % d this year .\ n ’ , name , age )
Alice will be 12 this year .
>> sprintf ( ’% s will be % d this year . ’ , name , age ) ;
>> sprintf ( ’% s will be % d this year . ’ , name , age )
ans =
’ Alice will be 12 this year . ’
>>

5
Dr. T. Diphofu University of Botswana

Key Difference

• fprintf: formats and prints output immediately.

• sprintf: formats and stores output as text.

If formatted text needs to be reused, saved, or combined with other output, sprintf should
be used. If formatted text only needs to be displayed, fprintf is more appropriate.

Using %s and %d with Line Feeds and Tabs


Example: Using Linefeed and Tabs for Aligned Output
The tab character \t inserts horizontal spacing and is useful for producing column-like
output. The line feed character \n moves the cursor to a new line after printing.
fprintf ( ’ Name \ t Age \ n ’)
fprintf ( ’% s \ t % d \ n ’ , name , age )

MATLAB output:
Name Age
Alice 12

Here, the tab character \t aligns the text into columns, improving readability.

7 Solving Equations in MATLAB


7.1 Solving Systems of Linear Equations
Many problems in mathematics, science, and engineering lead to systems of linear equations.
Such systems can be written in matrix form as

Ax = b,

where A is a matrix of coefficients, x is the vector of unknowns, and b is the right-hand-side


vector.
MATLAB solves systems of linear equations efficiently using matrix division.

Example: Solve the system of linear equations

x + y + z = 6,
2x − y + z = 3,
x + 2y − z = 3.

To solve this system numerically in MATLAB, we first write it in matrix form

Ax = b,

where      
1 1 1 x 6
A = 2 −1 1  , x = y  , b = 3 .
1 2 −1 z 3
The corresponding MATLAB commands are:

6
Dr. T. Diphofu University of Botswana

>>A = [1 1 1; 2 -1 1; 1 2 -1];
>>b = [6; 3; 3];
>>x = A \ b

x =
1.2857
2.1429
2.15714

This means that the solution of the system is

x = 1, y = 2, z = 3.

Interpretation
Matrix division computes the numerical solution of the system without explicitly computing
the inverse of A. This approach is faster, more accurate, and more stable than computing A−1 ,
and is therefore the preferred method in scientific computing.
This result means that the solution of the system is

x = 1, y = 2, z = 3.

Matrix division is fast, stable, and scales well to large systems, making it the standard ap-
proach in numerical computation.

Example: Solving a Quadratic Equation Numerically (built-in roots function)


Consider the quadratic equation

x2 − 4x + 3 = 0.

Instead of solving this equation symbolically, we rewrite it in a form suitable for numerical
computation. The roots of a quadratic equation

ax2 + bx + c = 0

can be computed using the quadratic formula.


In MATLAB, the coefficients are stored in a vector, and the built-in roots function is used.
>>p = [1 -4 3]; % coefficients of x ^2 - 4 x + 3
>>r = roots ( p )
r =
3
1

The numerical solution shows that the equation has two real roots,

x=1 and x = 3.

You might also like