This document discusses the evolution of digital circuit design and computer-aided design techniques. It describes how hardware description languages (HDLs) like Verilog emerged to allow designers to model digital circuits at different levels of abstraction. HDLs enabled logic synthesis which automated the translation from register transfer level designs to gate-level implementations. The document outlines typical design flows involving hierarchical modeling and top-down or bottom-up methodologies. It also covers key concepts in HDLs like modules, instances, and different levels of abstraction for module implementation. Finally, it discusses the components of a simulation including separate stimulus and design blocks.
3. Evolution of Computer Aided Digital Design
Digital circuit design has evolved rapidly over the last 25 years.
Earliest digital design were designed with Vacuum tubes and Transistors.
Integrated Circuits were then invented where logic gates were placed on a
single chip.
SSI (Small Scale Integration)
MSI (Medium Scale Integration) – 100s of gates on a chip
LSI (Large Scale Integration) – 1000s of gates on a chip ; Design process
started getting very complicated.
Computer Aided Design techniques began to evolve. Chip designers began
to uses circuit and logic simulation techniques to verify the functionality of
building blocks of the order of about 100 transistors. Circuits were still
tested on breadboard and layout was done on paper or by hand on graphic
computer terminal
www.ppk.110mb.com
4. …….
VLSI (Very Large Scale Integration) – more than 1’00’000 transistors. It
was not possible to verify these circuits on a breadboard.
Now CAD techniques become critical for verification and design of VLSI
digital circuits.
Computer programs to do automatic placement and routing of circuit
layouts became popular.
Designers were now building gate level digital circuits manually on
graphics terminals. They would build small building blocks and then derive
higher level blocks from them. And this process would continue until they
had built top-level block. Logic simulators came into existence to verify the
functionality of these circuits before they were fabricated on chip.
www.ppk.110mb.com
5. Emergence of HDLs
In the digital design field, designers felt the need for a standard language to describe
digital circuits. The Hardware Description Language (HDL) came into existence.
HDLs allowed the designers to model the concurrency of process found in hardware
elements.
The popular Hardware Description Languages are – Verilog HDL (in 1983) and
VHDL, both simulators used to simulate large digital circuits
Even though HDLs were popular for logic verification, designers had to manually
translate the HDL based design into a schematic circuit with interconnections
between gates.
With the advent of logic synthesis, digital circuits could be described at a Register
Transfer Level (RTL) by use of an HDL.
The designer had to specify how data flows between registers and how the design
processes the data.
The details of gates and their interconnections to implement the circuit were
automatically extracted by the logic synthesis tools from the RTL description
www.ppk.110mb.com
6. …………..
Thus, logic synthesis pushed the HDLs into the forefront of digital design.
Designer no longer had to manually place gates to build digital circuits.
They could describe complex circuits at an abstract level in terms of
functionality and data flow by designing those circuits in HDLs. Logic
synthesis tools would implement the specified functionality in terms of
gates and gate interconnections.
HDLs also began to be used for system level design. Used for simulation of
system boards, interconnect buses, FPGAs and PALs.
A common approach is to design each IC chip, using an HDL, and then
verify system functionality via simulation.
www.ppk.110mb.com
12. Design Methodologies
Two basic types of digital design Methodologies
Top – Down design Methodology
Bottom – Up design Methodology
www.ppk.110mb.com
13. Top – Down design Methodology
In this method we define the top-level block and identify the sub-blocks
necessary to build the top-level block. The sub – blocks are further
subdivided up to leaf-cells. Where leaf-cells are cells that cannot be sub
divided further.
www.ppk.110mb.com
14. Bottom – Up design Methodology
In bottom – up design methodology, the designer first identify the building
blocks that are available. Then bigger cells are obtained from these building
blocks. These cells are then used for higher level blocks until we build the
top level block in the design.
www.ppk.110mb.com
15. Hierarchical Modeling Concept
Typically, a combination of top-level and bottom-up flows is used.
Design architects define the specifications of the top-level block.
Logic designers decide how the design should be structured by breaking up
the functionality into blocks and sub-blocks.
At the same time, circuit designers are designing optimized circuits for leaf –
level cells. They build higher level cells by using these leaf cells.
The flow meets at an intermediate point where the switch-level circuit
designers have created a library of leaf cells by using switches, and logic
level designers have designed from top-down until all modules are defined
in terms of leaf cells.
www.ppk.110mb.com
16. Hierarchical Modeling Concept – Example
Negative Edge Triggered 4-bit ripple counter
The circuit is made up of negative edge triggered flip-flops (T_FF).
Each of the T_FF s can be made up from negative edge triggered D-Flip Flop
(D_FF) and inverters.
www.ppk.110mb.com
17. T – Flip Flop
Design Hierarchy
www.ppk.110mb.com
18. In a top down design methodology,
First specify the functionality of the ripple counter, which is the top level
block.
Then, implement the counter with T_FFs.
Build T_FF from the D_FF and an additional Inverter Gate.
In bottom-up methodology,
It flows in the opposite direction, combine small building blocks and build
bigger blocks – e.g Build D_FF from an ‘AND’ and ‘OR’ gates, or a
custom D_FF from transistors.
www.ppk.110mb.com
19. Modules
A module is the basic building block in Verilog.
A module can be an element or a collection of lower level design blocks.
Typically elements are grouped into modules to provide common
functionality that is used at many places in the design
A module provides the necessary functionality to the higher level block
through its port interface (Inputs & Outputs), but hides the internal
implementation. This allows the designer to modify module internals
without affecting the rest of the design.
Examples of modules : D_FF, T_FF (in the above example)
www.ppk.110mb.com
20. In Verilog, a module is decleared by the keyword ‘module’, and a corresponding
keyword ‘endmodule’ must appear at the end of the module definition.
Each module must have a ‘module_name’, which is the identifier for the module,
and a ‘module_terminal_list, which describes the input and output terminals of
the module.
module <module_name> (<module_terminal_list);
…
<module intervals>
…
…
end module
T- Flip Flop can be defined as module as follows
module T_FF (q, clock, reset);
…
<functionality of T- Flip Flop>
…
end module
www.ppk.110mb.com
21. Levels of Abstraction
Verilog is both a behavioral and a structural language.
Intervals of each module can be defined at four levels of abstraction, depending
on the needs of the design
Behavioral or Algorithmic Level
Dataflow level
Gate level
Switch level
The module behaves identically with the external environment irrespective of
the level of abstraction at which the module is described.
The intervals are hidden from the environment.
Thus, the level of abstraction to describe a module can be changed without any
change in the environment.
www.ppk.110mb.com
22. Behavioral or Algorithmic Level
This is the highest level of abstraction provided by Verilog HDL. A module
can be implemented in terms of the desired design algorithm without concern
for the hardware implementation details. Designing at this level is very
similar to C programming
www.ppk.110mb.com
23. Dataflow level
At this level the module is designed by specifying the data flow. The designer
to aware of how data flows between hardware registers and how the data is
processed in the design.
www.ppk.110mb.com
24. Gate level
The module is implemented in terms of logic gates and interconnections
between these gates. Design at this level is similar to describing a design in
terms of a gate level logic diagram.
www.ppk.110mb.com
25. Switch level
This is the lowest level of abstraction provided by Verilog. A module can be implemented in
terms of switches, storage nodes, and interconnection between them. Design at this level requires
knowledge of switch level implementation details .
www.ppk.110mb.com
26. Instances
A module provides a template from which we can create actual objects. When
a module is invoked, Verilog creates a unique object from the template.
Each object has its own name, variables, parameters and I/O interface.
The process of creating objects from a module template is called instantiation,
and objects are called ‘instances’.
In the example of ‘counter’, the top-level block creates four instances from the
T-Flip Flop (T_FF) template. Each T_FF instantiates a D_FF and an
inverter gate.
www.ppk.110mb.com
28. Components of a Simulation
Once a design block is completed, it must be tested. The functionality of
the design block can be tested by applying stimulus and checking results.
Such a block is called the stimulus block.
It is good practice to keep the stimulus and design blocks separate.
The stimulus block can be written in Verilog. A separate language is not
required to describe stimulus.
The stimulus block is also commonly called a ‘Test Bench’.
www.ppk.110mb.com
29. Types of Stimulus Application
Two styles of stimulus applications are possible.
In the first style, the ‘stimulus block instantiates the design block’ and
directly drives the signals in the design block.
In Stimulus Block Instantiates Design Block method, the stimulus block
becomes the top-level block. It manipulate sinals ‘clk’ and ‘reset’, and it
checks and displays output signal ‘q’
www.ppk.110mb.com
30. In the second style of applying stimulus is to ‘Instantiate both the Stimulus
and Design Blocks in a top-level dummy Module’. The stimulus block
interacts with the design block only through the interface.
In the fig. the stimulus module drives the signals d_clk and d_reset, which
are connected to the signals clk and reset in the design block. It also checks
and displays signals c_q, which is connected to the signal ‘q’ in the design
block. The function of the top-level block is simply to instantiate the design
and stimulus blocks.
www.ppk.110mb.com
31. Example – Ripple Carry Counter
Design Block
Let use top down design methodology
Verilog description of Ripple Carry Counter
module ripple_carry_counter (q, clk, reset);
output [3:0] q;
input clk, reset;
T_FF tff0 (q[0], clk, reset);
T_FF tff1 (q[1], clk, reset);
T_FF tff2 (q[2], clk, reset);
T_FF tff3 (q[3], clk, reset);
endmodule
www.ppk.110mb.com
32. In the above module, four instances of the module T_FF (T-Flip Flop) are
used. Therefore we must now define the internals of the module T_FF
module T_FF (q, clk, reset);
output q;
input clk, reset;
wire d;
D_FF dff0(q,d,clk,reset);
not n1(d,q);
endmodule
www.ppk.110mb.com
33. Since TFF instantiates D_FF, we must now define the internals of module
D_FF.
//module D_FF with synchronous reset
module D_FF (q, d, clk, reset);
output q;
input d, clk, reset;
reg q;
always @(posedge reset or negedge clk)
if (reset)
q=1’b0
else
q=d;
endmodule
www.ppk.110mb.com
34. Stimulus Block
Now stimulus block must be written for checking the ripple counter design
is functioning correctly.
In this case we must control the signals clk and reset so that the regular
function of the ripple counter and the synchronous reset mechanism are
both tested.
We can use waveforms for ‘clk’ and ‘reset’and its 4 bit output ‘q’ can be
viewed as shown below.
www.ppk.110mb.com
37. Basic Concepts in Verilog
Conventions
Whitespace – Blank space (b), tabs (t) and newlines (n) comprise the
whitespace
Comments – Comments are inserted in the code for readability and
documentation. There are two ways to write comments
1. A one line comment starts with ‘//’
2. Multiple line comment starts with ‘/*’ and ends with ‘*/’
Operators – Operators are three types
1. Unary – Unary operators precede the operand
2. Binary – Binary operators appear between two operands
3. Ternary – Ternary operators have two separate operators that
separate three operands
www.ppk.110mb.com
38. Number Specifications – Two types (Sized and Un-sized)
Sized numbers
Sized numbers are represented as <size> ‘ <base format> <number>
<size> is written only in decimal and specifies the number of bits in
the number
<base format> are (1) Decimal (d’ or ‘D)
(2) Hexadecimal (‘h or ‘H)
(3) Binary (‘b or ‘B)
(4) Octal (‘o or ‘O)
<number> is specified as consecutive digits from 0,1,….., e,f.
Example
4’b1111 //this is a four bit binary number ‘1111’
12’habc //this is a 12 bit hexadecimal number ‘abc’
16’d255 //this is a 16 bit decimal number ‘255’
www.ppk.110mb.com
39. Un-sized numbers
Numbers that are specified without a <size> specification have a default
number of bits (at least 32 bits) .
numbers that are specified without a <base format> are decimal numbers
by default
Example
23456 // this is a 32 bit decimal number by default
‘hc3 //this is a 32 bit hexadecimal number
‘o21 //this is a 32 bit octal number
X or Z values
An unknown value is denoted by an ‘X’
A high impedance value is denoted by ‘Z’
www.ppk.110mb.com
40. Negative Numbers
Negative numbers can be specified by putting a minus sign before the size
for a constant number.
Example
-6’d3 //8 bit negative number stored as 2’s complement of 3
Strings
A string is a sequence of characters that are enclosed by double quotes. The
string cannot be on multiple lines
Example
“Hello Verilog”
www.ppk.110mb.com
41. Identifiers and Keywords
Keywords are special identifiers reserved to define the language constructs.
Keywords are in lowercase
Identifiers are names given to objects so that they can be referenced in the
design. Identifiers are case sensitive and are made up of alphanumeric
characters, underscore (_) and the dollar sign($). They cannot start with a
number or a $ sign.
Example
reg value //reg is a keyword and value is an identifier
input clk //input is a keyword and clk is an identifier
www.ppk.110mb.com
42. Data Types
Value set
Verilog supports four values and eight strengths to model the functionality
of real hardware.
Value Level Condition in Hardware Circuits
0 Logic zero, false condition
1 Logic one , true condition
X Unknown Value
Z High impedance, floating state
In addition to the logic values, strength levels are often used to resolve
conflicts between drivers of different strengths in digital circuits.
www.ppk.110mb.com
43. Nets
Nets represent connections between hardware elements. Just as in real
circuits, nets have values continuously driven on them by the outputs of
devices that they are connected to.
Example
Net a is connected to the output of and Gate g1. Net a will continuously
assume the value computed at the output of gate g1.
Nets are declared primarily with the keyword ‘wire’. Nets are one bit
values by default. The terms wire and net are often used interchangeably.
The default value of a net is Z.
wire a; //declare net a for the above circuit
wire b,c; //declare two wires b, c for the above circuit
wire d=1’b0 //net d is fixed to logic value 0 at declaration
www.ppk.110mb.com
44. Registers
Registers represent data storage elements. Registers retain values until
another value is placed on them. In Verilog, the term registers means a
variable that can hold a value. Unlike a net, a register doesnot need a
driver. Verilog registers does not need a clock as hardware registers do.
Values of registers can be changed anytime in a simulation by assigning a
new value to the register.
register data types are commonly declared by the keyword ‘reg’ . The
default value for a register data type is ‘X’.
Example
reg reset //declare a variable reset
initial //this is a construct
begin
reset =1’b1; //initialize reset to ‘1’
#100 reset =1’b0; //after 100 time units reset is set to ‘0’
end
www.ppk.110mb.com
45. Vectors
Nets or reg data types can be declared as vectors (multiple bit width). If bit
width is not specified, the default is scalar (1 bit)
Example
wire a; //scalar net variable
wire [7:0] bus; // 8-bit bus
wire [32:0] busA, busB, busC; //3 buses of 32 bit width
reg clock; //scalar register
reg [7:0] clock; // 8bit register
www.ppk.110mb.com
46. Integer, Real and Time Register Data Types
Integer Data Type
An integer is a general purpose register data type used for manipulating
quantities. Integers are declared by the keyword ‘integer;. It is more
convenient to declare an integer variable for purposes such as counting.
Example :
integer counter;
initial
counter=1;
Real Number
Real number constants and real register data types are declared with the
keyword ‘real’.
Example:
real delta;
initial
begin
delta =2.31
end www.ppk.110mb.com
47. Time
Verilog simulation is done with respect to simulation time. A special time
register data type is used in verilog to store simulation time. A time
variable is declared with the keyword ‘time’.
The system function $time is invoked to get the current simulation time.
time simulation_time
initial
simulation_time=$time;
www.ppk.110mb.com
48. System tasks and Compiler Directives
System Tasks
All system tasks appear in the form $<keyword>. Operations such as displayin
on the screen, monitoring values of nets, stopping, and finishing are done
by system tasks.
Displaying information
$display is the main system task for displaying values of variables or
strings or expressions.
Example :
$display (p1,p2,…., pn);
p1,p2,,… can be strings or variables or expressions.
www.ppk.110mb.com
49. Monitoring Information
Verilog provides a mechanism to monitor a signal when its value changes.
This facility is provided by $monitor task.
Example:
$monitor (p1,p2,….pn).
Stopping and Finishing in a simulation
The task $stop is provided to stop during a simulation
$finish will terminate the simulation
www.ppk.110mb.com
50. Components of a Verilog Module
Module is the basic building block in a Verilog modeling. A Verilog module
consists of distinct parts as shown below.
www.ppk.110mb.com
51. A module definition always begins with the keyword ‘module’. The
module name, port list, port declarations, and optional parameters must
come first in a module definition.
The five components within a module are – variable declarations, dataflow
statements, instantiation of lower modules, behavioral blocks, and tasks or
functions.
The ‘endmodule’ statement must always come last in a module definition.
www.ppk.110mb.com
52. Example – SR Latch
// design program
module SR_latch (Q, Qbar, Sbar, Rbar);
output Q, Qbar;
input Sbar, Rbar;
nand n1 (Q, Sbar, Qbar);
nand n2 (Qbar, Rbar, Q);
endmodule
// test bench proram
module testbench
wire q, qbar;
reg set, reset;
SR_latch m1(q, qbar, set, reset); //instantiate the SR latch with name m1
initial
begin
$monitor ($time, “set=%b, reset =%b, q=%b n”, set, reset, q);
set=0; reset=0;
#5 reset =1;
#5 reset=0;
#5 set=1;
end
endmodule
www.ppk.110mb.com
53. Gate Level Modeling
The low level abstraction is the ‘Gate Level’ abstraction. At gate level, the
circuit is described in terms of gates. Hardware designer in this level
requires basic knowledge of digital logic design.
Gate types
Verilog supports basic logic gates as predefined ‘primitives’. All logic
circuits can be designed by using basic gates.
There are two classes of basic gates : and/or gates and buf/not gates
and / or gates have one scalar output and multiple scalar inputs. The
available gates in this category are – and, nand, or, nor, xor and xnor.
buf/ not gates have one scalar input and one or more scalar outputs
www.ppk.110mb.com
54. Example – Multiplexer
module mux4_to_1 (out, i0, i1, i2, i3, s1, s0);
output out;
input i0, i1, i2, i3;
input s1, s0;
wire s1n, s0n;
wire y0, y1, y2, y3;
not (s1n, s1);
not (s0n, s0);
and (y0, i0, s1n, s0n);
and (y1, i1, s1n, s0);
and (y2, i2, s1, s0n);
and (y3, i3, s1, s0);
or (out, y0, y1, y2, y3);
endmodule
www.ppk.110mb.com
56. Example – Full Adder
module fulladd (sum, c_out, a, b, c_in);
output sum, c_out;
input a, b, c_in;
wire s1, c1, c2;
xor (s1, a, b);
and (c1, a, b);
xor (sum, s1, c_in);
and (c2, s1, c_in);
or (c_out, c2, c1);
endmodule
www.ppk.110mb.com
58. Data Flow Modeling
Modeling in Gate level is very difficult for a complex circuit design. Data
flow modeling provides a powerful way to implement a design. Verilog
allows a circuit to be designed in terms of the dataflow between registers
and process data rather than instantiation of individual gates.
Currently, automated tools are used to create a gate level circuit from a
dataflow design description. This process is called Logic Synthesis.
This approach allows a designer to concentrate on optimizing the design in
terms of data flow.
For maximum flexibility in the design process, designers typically use a
Verilog description style that combines the concepts of Gate-level, Data-
flow and Behavioral design.
Dataflow modeling describes the design in terms of expressions instead of
Primitive Gates.
Expressions, Operators and Operands form the basics of Dataflow
modeling.
www.ppk.110mb.com
59. Expressions –
Are constructs that combine operators and operands to produce a result.
Example : a=b^c; // bit wise XOR
assign out= S1? (S2: S3);
Operands –
Operands can be any one of the data types. Operands can be constants,
integers, real numbers, nets, registers, times, etc…
Example : real a, b c; // a, b and c are real type variables
c=a-b; // a, b and c are used as operands.
Operators –
Operators act on the operands to produce desired result.
Example : &&, !, >> //unary, binary or ternary operators
www.ppk.110mb.com
61. Behavioral Modeling
Architectural evaluation takes place at an algorithmic level, where the
designers do not necessarily think in terms of logic gates and data flow, but
in terms of the behavior of the algorithm and its performance.
Verilog provides designers the ability to describe design functionality in an
algorithmic manner.
In other words, the designer describes the behavior of the circuit.
Behavioral modeling is the high level of abstraction.
Design at this level resembles C programming than a circuit design.
It provides a great amount of flexibility to the designer.
There are two structured procedure statements in Verilog – Always and
Initial
www.ppk.110mb.com
62. Assignment
1. Explain different types of operators used in Verilog modeling, with
suitable examples
2. Design a 4 to 1 multiplexer using logic equations and conditional
operators in dataflow modeling.
3. Design a 4 bit full adder using Verilog modeling.
4. Design a Ripple Counter using Verilog Modeling.
www.ppk.110mb.com
65. THE EVOLUTION OF PROGRAMMABLE DEVICES
1. Programmable Read Only Memories (PROMs)
2. Programmable Logic Arrays (PLAs)
3. Programmable Array Logic (PALs)
4. CPLDs and FPGAs
www.ppk.110mb.com
66. Programmable Read Only Memories (PROMs)
Programmable Read Only Memories, or PROMs, are simply memories that
can be inexpensively programmed by the user to contain a specific pattern.
(This pattern can be used to represent a microprocessor program, a simple
algorithm, or a state machine.)
Some PROMs can be programmed once only. Other PROMs, such as
EPROMs or EEPROMs can be erased and programmed multiple times.
PROMs are excellent for implementing any kind of combinational logic
with a limited number of inputs and outputs.
For sequential logic, external clocked devices such as flip-flops or
microprocessors must be added.
PROMs tend to be extremely slow, so they are not useful for applications
where speed is an issue.
www.ppk.110mb.com
67. Programmable Logic Arrays (PLAs)
Programmable Logic Arrays (PLAs) were a solution to the speed and input
limitations of PROMs.
PLAs consist of a large number of inputs connected to an AND plane, where
different combinations of signals can be logically ANDed together according to
how the part is programmed. The outputs of the AND plane go into an OR
plane, where the terms are ORed together in different combinations and finally
outputs are produced.
At the inputs and outputs there are typically inverters so that logical NOTs can
be obtained.
These devices can implement a large number of combinatorial functions.
However, they generally have many more inputs and are much faster.
www.ppk.110mb.com
68. Programmable Array Logic (PALs)
The Programmable Array Logic (PAL) is a variation of the PLA.
Like the PLA, it has a wide, programmable AND plane for ANDing inputs
together. However, the OR plane is fixed, limiting the number of terms that can be
ORed together.
Other basic logic devices, such as multiplexers, exclusive ORs, and latches are
added to the inputs and outputs. Most importantly, clocked elements, typically flip-
flops, are included.
These devices are now able to implement a large number of logic functions
including clocked sequential logic need for state machines.
PALs are also extremely fast.
www.ppk.110mb.com
69. CPLDs and FPGAs
Ideally the hardware designer wanted something that gave him the flexibility and
complexity of an ASIC but with the shorter turn-around time of a programmable
device.
The solution came in the form of two new devices - the Complex Programmable
Logic Device (CPLD) and the Field Programmable Gate Array.
CPLDs and FPGAs bridge the gap between PALs and Gate Arrays. CPLDs are as
fast as PALs but more complex. FPGAs approach the complexity of Gate Arrays but
are still programmable
www.ppk.110mb.com
70. Complex Programmable Logic Devices (CPLDs)
Complex Programmable Logic Devices (CPLDs) are exactly what they
claim to be.
Essentially they are designed to appear just like a large number of PALs in
a single chip, connected to each other through a cross point switch
They use the same development tools and programmers, and are based on
the same technologies, but they can handle much more complex logic and
more of it.
www.ppk.110mb.com
71. CPLD Architecture
The internal architecture of a CPLD consists of the following blocks
Function blocks
Input/output block
Interconnect matrix and
Programmable elements.
www.ppk.110mb.com
73. The AND plane still exists as shown by the crossing wires.
The AND plane can accept inputs from the I/O blocks, other function
blocks, or feedback from the same function block.
The terms and then ORed together using a fixed number of OR gates, and
terms are selected via a large multiplexer. The outputs of the mux can then
be sent straight out of the block, or through a clocked flip-flop.
This particular block includes additional logic such as a selectable
exclusive OR and a master reset signal, in addition to being able to program
the polarity at different stages.
Usually, the function blocks are designed to be similar to existing PAL
architectures, so that the designer can use familiar tools or even older
designs without changing them.
www.ppk.110mb.com
75. The I/O block is used to drive signals to the pins of the CPLD device at the
appropriate voltage levels with the appropriate current.
Usually, a flip-flop is included. This is done on outputs so that clocked
signals can be output directly to the pins without encountering significant
delay. It is done for inputs so that there is not much delay on a signal before
reaching a flip-flop which would increase the device hold time
requirement.
Also, some small amount of logic is included in the I/O block simply to add
some more resources to the device.
www.ppk.110mb.com
76. Interconnect
The CPLD interconnect is a very large programmable switch matrix that
allows signals from all parts of the device go to all other parts of the device.
While no switch can connect all internal function blocks to all other
function blocks, there is enough flexibility to allow many combinations of
connections.
www.ppk.110mb.com
77. Programmable Elements
Different manufacturers use different technologies to implement the
programmable elements of a CPLD.
The common technologies are Electrically Programmable Read Only
Memory (EPROM), Electrically Erasable PROM (EEPROM) and Flash
EPROM.
www.ppk.110mb.com
78. CPLD Architecture Issues
When considering a CPLD for use in a design, the following issues should
be taken into account
1. The programming technology
EPROM, EEPROM, or Flash EPROM? This will determine the equipment
needed to program the devices and whether they came be programmed only
once or many times.
www.ppk.110mb.com
79. 2. The function block capability
How many function blocks are there in the device?
How many product and sum terms can be used?
What are the minimum and maximum delays through the logic?
What additional logic resources are there such as XNORs, ALUs, etc.?
What kind of register controls are available (e.g., clock enable, reset,
preset, polarity control)? How many are local inputs to the function block
and how many are global, chip-wide inputs?
What kind of clock drivers are in the device and what is the worst case
skew of the clock signal on the chip. This will help determine the
maximum frequency at which the device can run.
www.ppk.110mb.com
80. 3. The I/O capability
How many I/O are independent, used for any function, and how many are
dedicated for clock input, master reset, etc.?
What is the output drive capability in terms of voltage levels and current?
What kind of logic is included in an I/O block that can be used to increase
the functionality of the design?
www.ppk.110mb.com
81. Example CPLD Families
Some CPLD families from different vendors are listed below:
Altera MAX 7000 and MAX 9000 families
Atmel ATF and ATV families
Lattice ispLSI family
Lattice (Vantis) MACH family
Xilinx XC9500 family
www.ppk.110mb.com
82. Field Programmable Gate Arrays (FPGAs)
Field Programmable Gate Arrays are having a structure similar to a PAL or
other programmable device, they are structured very much like a gate array
ASIC. This makes FPGAs very nice for use in prototyping ASICs, or in
places where and ASIC will eventually be used.
For example, an FPGA maybe used in a design that need to get to market
quickly regardless of cost. Later an ASIC can be used in place of the FPGA
when the production volume increases, in order to reduce cost.
www.ppk.110mb.com
83. FPGA Architecture
The architecture consists of configurable logic blocks, configurable I/O blocks, and programmable
interconnect.
Also, there will be clock circuitry for driving the clock signals to each logic block, and additional logic
resources such as ALUs, memory, and decoders may be available.
The two basic types of programmable elements for an FPGA are Static RAM and anti-fuses.
www.ppk.110mb.com
84. Configurable Logic Blocks (CLBs)
Configurable Logic Blocks contain the logic for the FPGA. In a large grain
architecture, these CLBs will contain enough logic to create a small state machine.
In a fine grain architecture, more like a true gate array ASIC, the CLB will contain
only very basic logic.
The large grain block contains RAM for creating arbitrary combinatorial logic
functions. It also contains flip-flops for clocked storage elements, and multiplexers
in order to route the logic within the block and to and from external resources. The
muxes also allow polarity selection and reset and clear input selection.
www.ppk.110mb.com
85. Configurable I/O Blocks
A Configurable I/O Block is used to bring signals on to the chip and send them back off
again. It consists of an input buffer and an output buffer with three state and open collector
output controls.
Typically there are pull up resistors on the outputs and sometimes pull down resistors.
The polarity of the output can usually be programmed for active high or active low output
The slew rate of the output can be programmed for fast or slow rise and fall times.
A flip-flop on outputs so that clocked signals can be output directly to the pins without
encountering significant delay.
www.ppk.110mb.com
86. Programmable Interconnect
The interconnect of an FPGA is very different than that of a CPLD, but is rather similar to
that of a gate array ASIC.
In FPGA a hierarchy of interconnect resources can be seen. There are long lines which can be
used to connect critical CLBs that are physically far from each other on the chip without
inducing much delay. They can also be used as buses within the chip.
There are also short lines which are used to connect individual CLBs which are located
physically close to each other.
There is often one or several switch matrices, like that in a CPLD, to connect these long and
short lines together in specific ways.
Programmable switches inside the chip allow the connection of CLBs to interconnect lines
and interconnect lines to each other and to the switch matrix.
Special long lines, called global clock lines, are specially designed for low impedance and
thus fast propagation times. These are connected to the clock buffers and to each clocked
element in each CLB.
www.ppk.110mb.com
87. Clock Circuitry
Special I/O blocks with special high drive clock
buffers, known as clock drivers, are distributed
around the chip. These buffers are connect to clock
input pads and drive the clock signals onto the global
clock lines. These clock lines are designed for low
skew times and fast propagation times.
www.ppk.110mb.com
88. Small Grain and Large Grain FPGA
Small grain contain only small, very basic elements such as NAND gates, NOR
gates, etc. The philosophy is that small elements can be connected to make larger
functions without wasting too much logic.
In a large grain FPGA, where the CLB can contain two or more flip-flops, a design
which does not need many flip-flops will leave many of them unused.
Unfortunately, small grain architectures require much more routing resources, which
take up space and insert a large amount of delay which can more than compensate
for the better utilization.
www.ppk.110mb.com
89. SRAM and Anti-fuse Programming
There are two methods of programming FPGAs based on the
programming element.
SRAM Based
Anti-fuse based
www.ppk.110mb.com
90. SRAM based FPGA
The first, SRAM programming, involves small Static RAM bits for each
programming element. Writing the bit with a zero turns off a switch, while
writing with a one turns on a switch.
www.ppk.110mb.com
91. Advantages and Disadvantages of SRAM
The advantages of SRAM based FPGAs is that they use a standard fabrication
process that chip fabrication plants are familiar with and are always optimizing for
better performance. Since the SRAMs are reprogrammable, the FPGAs can be
reprogrammed any number of times, even while they are in the system, just like
writing to a normal SRAM.
The disadvantages are that they are volatile, which means a power glitch could
potentially change it. Also, SRAMbased devices have large routing delays.
www.ppk.110mb.com
92. Anti-fuse based FPGA
The other method involves anti-fuses which consist of microscopic
structures which, unlike a regular fuse, normally makes no connection. A
certain amount of current during programming of the device causes the two
sides of the anti-fuse to connect.
www.ppk.110mb.com
93. Advantages and Disadvantages of Anti-fuse
The advantages of Anti-fuse based FPGAs are that they are non-volatile
and the delays due to routing are very small, so they tend to be faster.
The disadvantages are that they require a complex fabrication process, they
require an external programmer to program them, and once they are
programmed, they cannot be changed.
www.ppk.110mb.com
94. Example FPGA Families
Examples of SRAM based FPGA families include the following:
Altera FLEX family
Atmel AT6000 and AT40K families
Lucent Technologies ORCA family
Xilinx XC4000 and Virtex families
Examples of Anti-fuse based FPGA families include the following:
Actel SX and MX families
Quicklogic pASIC family
www.ppk.110mb.com
96. Applications of CPLD
complex designs, such as graphics controller, LAN controllers,
UARTs, cache control
www.ppk.110mb.com
97. Applications of FPGAs
FPGAs have gained rapid acceptance over the past decade because users
can apply them to a wide range of applications:
Random logic,
Integrating multiple SPLDs
Device controllers
Communication encoding and filtering,
Small- to medium-size systems with SRAM blocks,
Prototyping designs
Emulation of entire large hardware systems via the use of many
interconnected FPGAs.
Custom computing machines
www.ppk.110mb.com
100. Linear Algebra
Matrix Analysis
Linear Equations
Eigen values and Singular Values
Matrix Logarithms and Exponentials
Factorization
www.ppk.110mb.com
101. Data Analysis and Fourier
Transforms
Basic Operations
Finite Differences
Correlation
Filtering and Convolution
Fourier Transforms
www.ppk.110mb.com
102. Signal Processing
The Signal Processing Toolbox is a collection of tools built on the MATLAB numeric computing
environment. The toolbox supports a wide range of signal processing operations, from waveform
generation to filter design and implementation, parametric modelling, and spectral analysis. The toolbox
provides two categories of tools
Command line functions in the following categories:
Analog and digital filter analysis
Digital filter implementation
FIR and IIR digital filter design
Analog filter design
Filter discretization
Spectral Windows Transforms
Cepstral analysis
Statistical signal processing and spectral analysis
Parametric modeling
Linear Prediction
Waveform generation
A suite of interactive graphical user interfaces for
Filter design and analysis
Window design and analysis
Signal plotting and analysis
Spectral analysis
www.ppk.110mb.com
103. Polynomials and Interpolation
Polynomials
Functions for standard polynomial operations. Additional topics include
curve fitting and partial fraction expansion.
Interpolation
Two- and multi-dimensional interpolation techniques, taking into account
speed, memory, and smoothness considerations.
www.ppk.110mb.com
104. External Interfaces
MATLAB provides interfaces to external routines written in other
programming languages, data that needs to be shared with external
routines, clients or servers communicating via Component Object Model
(COM) or Dynamic Data Exchange (DDE), and peripheral devices that
communicate directly with MATLAB.
Much of this interface capability was formerly referred to under the title of
the MATLAB Application Program Interface, or API.
www.ppk.110mb.com
106. Basic Components of the
MATLAB Environment
MATLAB has the following basic window components:
Launch Pad Window
- to access all MATLAB services and toolboxes
Command Window
- to execute commands in the MATLAB environment
Current Directory Window
- to quickly access files on the MATLAB path
Figure Window
- to display graphical output from MATLAB code
Workspace Window
- to view variable definitions and variable memory allocations
M-File Editor/Debugger Window
- to write M-files (includes color-coded syntax features) to debug M-files interactively (break
points)
MATLAB Path Window
- to add and delete folders to the MATLAB path
Command History Window
- displays all commands issued in MATLAB since the last session (good for learning and
verification
www.ppk.110mb.com
107. A new Java-based GUI environment allows you to easily navigate
between various windows
www.ppk.110mb.com
108. MATLAB Command Window
The command window allows you to interact with
MATLAB just as if you type things in a calculator
Cut and paste operations ease the repetition of tasks
Use ‘up-arrow’ key to repeat commands (command
history)
www.ppk.110mb.com
109. MATLAB Launch Pad Window
The launch window allows you to quickly select among various MATLAB
components and toolboxes
It will Show the installed toolboxes in the launch window environment
www.ppk.110mb.com
110. MATLAB Current Directory
Window
Provides quick access to all files available in your Path
Provides a brief description (when files are commented out) of
each M-file
www.ppk.110mb.com
111. MATLAB Editor/Debugger
Window
Provides the same functionality found in most programming language
development environments
- Color codes MATLAB built-in functions (blue color)
- Easy access to cut, paste, print, and debug operations
- Checks balance in MATLAB function syntax
www.ppk.110mb.com
112. MATLAB Editor/Debugger
MATLAB has an interactive debugger to help you step through your source
code. This debugger has many of the same functional features found in
high-level programming languages (i.e., FORTRAN, C/C++, etc.).
www.ppk.110mb.com
113. MATLAB Debugger
Allows standard programming techniques such:
- Breakpoints
- Break on error, warnings and overflows
- Step in and out of script
- Function dependencies
www.ppk.110mb.com
114. MATLAB Figure Window
Displays the graphic contents of MATLAB code (either from Command
Window, an M-file, or output from MEX file)
Figure properties can be changed interactively using the following
commands:
PlotEdit
- allows interactive changes to plots (add legend, lines,arrows, etc.)
- This function is automatically invoked in MATLAB 5.3 and higher
versions
PropEdit
- Allows changes to all Handle Graphic properties in a MATLAB plot
www.ppk.110mb.com
115. MATLAB Workspace
As we develop and execute models in MATLAB the workspace stores all
variables names and definitions for you. All variables are usually available
to you unless the workspace is clear with the ‘>>clear’ command.
www.ppk.110mb.com
116. MATLAB Figure Property Editor
Allows you to change properties of a plot
www.ppk.110mb.com
117. Matlab Help Window
Provides access to various help files (both internal and online files
available on the web)
www.ppk.110mb.com
118. MATLAB Path Window
Shows all folders contained in the MATLAB path
Allows you to include other folders from within MATLAB can be executed
www.ppk.110mb.com
119. MATLAB Command History
Window
Displays all previous commands issued in a MATLAB session
Good for verification of computation sequences and for learning
www.ppk.110mb.com
121. Interactive Mode
Use the MATLAB Command Window to interact with MATLAB in
“calculator” mode
>> a=[3 2 4; 4 5 6; 1 2 3]
Multiple commands can be executed using the semicolon “;” separator
between commands
>> a=[3 2 4; 4 5 6; 1 2 3] ; b=[3 2 5]’ ; c=a*b
This single line defines two matrices (a and b) and computes their product
(c)
Use the semi-colon “;” separator to tell the MATLAB to inhibit output to
the Command Window
Semi-colon is also used to differentiate between rows in a matrix definition
All commands can be executed within the MATLAB Command Window
www.ppk.110mb.com
122. General Purpose Commands
On Line Help
help list topics on which help is available
helpwin help window with hypertext navigation
helpdesk opens web browser based help facility
help topic provides help on topic
lookfor string lists help topics containing string
demo runs MATLAB demos from a MATLAB created
Graphic User Interface (GUI)
Workspace informations
ver tells you the version of MATLAB being used
who lists all variables in the current workspace
whos lists all variables in the workspace including array sizes
clear clears all variables and functions from memory
pack consolidates workspace memory
load load workspace variables from disk (from a previous session)
save saves all variables and functions in the workspace to disk
what lists MATLAB files in directory
edit edits a MATLAB M-file
diary save text of MATLAB session
clf clear figure window
clc clears command window
what lists M, Mat, and Mex files on the desk
www.ppk.110mb.com
123. Directory information
pwd shows current working directory
cd changes current working directory
dir list contents of current directory
ls lists contents of current directory same as dir
path gets or sets MATLAB search path
editpath modifies MATLAB search path
copyfile copies a file
mkdir creates a directory
General information
Computer tells about the computer you are using
clock Gives the time
date gives the date
more controls the paged outputs according to screen size
ver gives license and version information
bench benchmark your computer on running MATLAB, compared to other
computers
Termination
^c abort current command execution
quit quits MATLAB
exit same as quit
124. File Types
M Files
Mat Files
Fig Files
P Files
Mex Files
125. Creating MATLAB Files
Two ways to interact with MATLAB:
Interactive console mode - allows you to do computations and plots from
the command line
Through M-files - saves your “code” in a text file (with.m termination)
allowing you to reuse any function or algorithm in it
Other types of files in MATLAB are MAT (binary) and MEX (executable)
files
www.ppk.110mb.com
126. MATLAB M-Files
M-files can be saved, refined and reused as needed
These files end in “.m” in all platforms
Use the MATLAB editor to accomplish this task
Any word processor can also be used (save files as text)
www.ppk.110mb.com
127. MATLAB Binary Files
These files are convenient to store information that needs to be reused
MATLAB binary files end in .mat
MATLAB mat files are platform independent
Use the “save” command at the MATLAB command line.
- save (saves all workspace variables to matlab.mat)
- save fname (saves all workspace to fname.mat)
- save fname x y (saves x and y to fname.mat)
- save fname x y -ascii (saves x and y in 8-digit text format)
- save fname x y -ascii -double -tabs (tab delimited format)
www.ppk.110mb.com
128. Properties of Binary Files
Binary files are compact files only interpreted by MATLAB
Good to store data to be reused later on
Easy to transfer among PCs (compact size)
- This works well across platforms
- MATLAB 6.0 has good binary files backward compatibility
Easy to retrieve and work with using the ‘load’command
Fast retrieval
www.ppk.110mb.com
129. Loading Binary Files
Binary files can be loaded simply issuing the ‘load’
MATLAB command.
Identified by .mat ending (e.g., traffic.mat)
www.ppk.110mb.com
130. Importing Data into MATLAB
There are several ways to enter data in MATLAB:
Explicitly as elements of a matrix in MATLAB
Creating data in an M-file
Loading data from ASCII files
Use the Import Wizard in MATLAB (6.0 version only)
Reading data using MATLAB’s I/O functions (fopen, fread, etc.)
Using specialized file reader functions (wk1read, imread, wavread,
dlmread)
Develop an MEX-file to read the data (if FORTRAN or C/C++ routines
exist)
www.ppk.110mb.com
131. Exporting Data from MATLAB
There are several ways to export data from MATLAB:
Use the diary command (only for small arrays)
ASCII (use the save command with ‘-ascii’ option)
Use the function dlmwrite to specify any delimiters needed
Save data to a file in any specific format (use fopen, fwrite and other
MATLAB I/O functions)
Use specialized MATLAB write functions such as:
- dlmwrite (user-defined delimeter ascii file)
- wk1write (spreadsheet format)
- imwrite and so on
www.ppk.110mb.com
132. Minimum Matlab Session
Starting MATLAB
On Windows platforms, start MATLAB by double-clicking the MATLAB
shortcut icon on your Windows desktop.
On UNIX platforms, start MATLAB by typing matlab at the operating
system prompt.
You can customize MATLAB startup. For example, you can change the
directory in which MATLAB starts or automatically execute MATLAB
statements in a script file named startup.m.
Quitting MATLAB
To end your MATLAB session, select File -> Exit MATLAB in the
desktop, or type quit in the Command Window. You can run a script file
named finish.m each time MATLAB quits that, for example, executes
functions to save the workspace, or displays a quit confirmation dialog box.
www.ppk.110mb.com
133. Arithmetic Operators (+ - * / ^ ‘ )
Syntax
A+B + Addition or unary plus. A+B adds A and B. A and B must have the same size, unless one is a scalar. A
scalar can be added to a matrix of any size.
A-B - Subtraction or unary minus. A-B subtracts B from A. A and B must have the same size, unless one is a
scalar. A scalar can be subtracted from a matrix of any size.
A*B Matrix multiplication. C = A*B is the linear algebraic product of the matrices A and B.
A.*B .* Array multiplication. A.*B is the element-by-element product of the arrays A and B. A and B must have the
same size, unless one of them is a scalar.
A/B / Slash or matrix right division. B/A is roughly the same as B*inv(A)
A./B ./ Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B must have the same size, unless
one of them is a scalar.
AB Backslash or matrix left division. If A is a square matrix, AB is roughly the same as inv(A)*B, except it is
computed in a different way.
A.B . Array left division. A.B is the matrix with elements B(i,j)/A(i,j). A and B must have the same size, unless
one of them is a scalar.
A^B ^ Matrix power. X^p is X to the power p, if p is a scalar. If p is an integer, the power is computed by repeated
squaring. If the integer is negative, X is inverted first.
A.^B .^ Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A and B must have the same size,
unless one of them is a scalar.
A‘ ' Matrix transpose. A' is the linear algebraic transpose of A. For complex matrices, this is the complex
conjugate transpose.
A.’ .' Array transpose. A.' is the array transpose of A. For complex matrices, this does not involve conjugation.
www.ppk.110mb.com
135. Exponential
exp Exponential
expm1 Exponential of x minus 1
log Natural logarithm
log1p Logarithm of 1+x
log2 Base 2 logarithm and dissect floating-point numbers into
exponent and mantissa
log10 Common (base 10) logarithm
nextpow2 Next higher power of 2
pow2 Base 2 power and scale floating-point number
reallog Natural logarithm for nonnegative real arrays
realpow Array power for real-only output
realsqrt Square root for nonnegative real arrays
sqrt Square root
nthroot Real nth root
www.ppk.110mb.com
136. Complex Functions
abs Absolute value
angle Phase angle
complex Construct complex data from real and imaginary parts
conj Complex conjugate
cplxpair Sort numbers into complex conjugate pairs
i Imaginary unit
imag Complex imaginary part
isreal True for real array
j Imaginary unit
real Complex real part
sign Signum
unwrap Unwrap phase angle
www.ppk.110mb.com
137. Arrays (Array Operations)
[ ] Array constructor
, Array row element separator
; Array column element separator
: Specify range of array elements
end Indicate last index of array
+ Addition or unary plus
- Subtraction or unary minus
.* Array multiplication
./ Array right division
. Array left division
.^ Array power
.‘ Array (nonconjugated) transpose
www.ppk.110mb.com
139. Creating and printing simple plots
Syntax
plot(Y)
plot(X1,Y1,...)
plot(X1,Y1,LineSpec,...)
plot(...,'PropertyName',PropertyValue,...)
plot(axes_handle,...)
h = plot(...)
hlines = plot('v6',...)
www.ppk.110mb.com
140. plot(Y)
plot(Y)
plots the columns of Y versus their index if Y is a real number. If Y is
complex, plot(Y) is equivalent to plot(real(Y),imag(Y)).
www.ppk.110mb.com
141. plot(X1,Y1,...)
plot(X1,Y1,...) plots all lines defined by Xn versus Yn pairs. If only Xn or Yn
is a matrix, the vector is plotted versus the rows or columns of the matrix,
depending on whether the vector's row or column dimension matches the
matrix.
Example:
x=[1 2 3 4 5];
y=[2 4 6 1 3];
plot (x,y)
www.ppk.110mb.com
142. plot(X1,Y1,LineSpec,...)
plot(X1,Y1,LineSpec,...) plots all lines defined by the Xn,Yn,LineSpec triples,
where LineSpec is a line specification that determines line type, marker
symbol, and color of the plotted lines.
Example:
plot(x,y,'-.or')
plots y versus x using a dash-dot line (-.), places circular markers (o) at the
data points, and colors both line and marker red (r)
www.ppk.110mb.com
143. Line Styles
Line specification syntax :: plot(X1,Y1,LineSpec,...)
It specifies the properties of lines used for plotting. MATLAB enables you to
define many characteristics, including Line style Line width Color Marker type
Marker size Marker face and edge coloring (for filled markers)
MATLAB defines string specifiers for line styles, marker types, and colors.
For example, plot(x,y,'-.or')
www.ppk.110mb.com
Color Specifiers
r Red
g Green
b Blue
c Cyan
m Magenta
y Yellow
k Black
w White
Line Style Specifiers
- Solid line (default)
-- Dashed line
: Dotted line
-. Dash-dot line
Marker Specifiers
+ Plus sign
o Circle
* Asterisk
. Point
x Cross
s Square
145. Multiple data set in one graph
plot(x,y1,x,y2,x,y3)
>> x=[0:0.25:3*pi];
>> y1=sin(x);
>> y2=cos(x);
>> y3=tan(x);
>> plot(x,y1,x,y2,x,y3)
www.ppk.110mb.com
146. Sub Plot
subplot divides the current figure into rectangular panes that are numbered
rowwise. Each pane contains an axes. Subsequent plots are output to the
current pane.
subplot(m,n,p) creates an axes in the pth pane of a figure divided into an m-by-
n matrix of rectangular panes.
>> subplot(2,2,1)
>> subplot(2,2,2)
>> subplot(2,2,3)
>> subplot(2,2,4)
www.ppk.110mb.com
147. scircle1
Compute coordinates of a small circle path from center, radius, and arc limits
Syntax
[latc,lonc] = scircle1(lat,lon,rng) returns the coordinates of points along small
circles centred at the points provided in lat and lon with radii given in rng.
These radii must in this case be given in the same angle units as the centre
points ('degrees').
Example:
[a,b]=scircle1(1,1,3);
plot(a,b)
www.ppk.110mb.com
148. scircle2
Compute coordinates of a small circle path from center and perimeter point
Syntax
[latc,lonc] = scircle2(lat1,lon1,lat2,lon2) returns the coordinates of points along
small circles centred at the points provided in lat1 and lon1, which pass
through the points provided in lat2 and lon2.
Example:
[a,b]=scircle2(1,1,3,3);
plot(a,b)
www.ppk.110mb.com
149. Plot polar coordinates
Syntax
polar(theta,rho)
polar(theta,rho,LineSpec)
The polar function accepts polar coordinates,
plots them in a Cartesian plane, and draws
the polar grid on the plane.
polar(theta,rho) creates a polar coordinate plot
of the angle theta versus the radius rho.
theta is the angle from the x-axis to the
radius vector specified in radians; rho is the
length of the radius vector specified in
dataspace units.
Example:
t = 0:.01:2*pi;
polar(t,sin(2*t))
>> t = 0:.01:2*pi;
>> polar(t,sin(2*t).*cos(2*t))
150. Annotating Plots
Annotation Create annotation objects
clabel Add contour labels to contour plot
datetick Date formatted tick labels
gtext Place text on 2-D graph using mouse
legend Graph legend for lines and patches
texlabel Produce the TeX format from character string
title Titles for 2-D and 3-D plots
xlabel X-axis labels for 2-D and 3-D plots
ylabel Y-axis labels for 2-D and 3-D plots
zlabel Z-axis labels for 3-D plots
151. Script file (Script M-files)
A script file is an external file that contains a sequence of MATLAB statements.
By typing the filename, you can obtain subsequent MATLAB input from the
file. Script files have a filename extension of .m and are often called M-files.
Scripts are the simplest kind of M-file. They are useful for automating blocks of
MATLAB commands, such as computations you have to perform repeatedly
from the command line. Scripts can operate on existing data in the workspace,
or they can create new data on which to operate. Although scripts do not return
output arguments, any variables that they create remain in the workspace, so
you can use them in further computations. In addition, scripts can produce
graphical output using commands like plot.
Scripts can contain any series of MATLAB statements. They require no
declarations or begin/end delimiters.
Like any M-file, scripts can contain comments. Any text following a percent sign
(%) on a given line is comment text. Comments can appear on lines by
themselves, or you can append them to the end of any executable line.
www.ppk.110mb.com
152. Function (Function M-files)
Syntax
function [out1, out2, ...] = funname(in1, in2, ...)
function [out1, out2, ...] = funname(in1, in2, ...) defines function funname that
accepts inputs in1, in2, etc. and returns outputs out1, out2, etc.
You add new functions to the MATLAB vocabulary by expressing them in terms
of existing functions. The existing commands and functions that compose the new
function reside in a text file called an M-file.
M-files can be either scripts or functions. Scripts are simply files containing a
sequence of MATLAB statements. Functions make use of their own local
variables and accept input arguments.
The name of an M-file begins with an alphabetic character and has a filename
extension of .m. The M-file name, less its extension, is what MATLAB searches
for when you try to use the script or function. A line at the top of a function M-file
contains the syntax definition. The name of a function, as defined in the first line
of the M-file, should be the same as the name of the file without the .m extension.
The variables within the body of the function are all local variables.
www.ppk.110mb.com
153. You can terminate any function with an end statement but, in most cases, this
is optional. end statements are required only in M-files that employ one or
more nested functions. Within such an M-file, every function (including
primary, nested, private, and subfunctions) must be terminated with an end
statement. You can terminate any function type with end, but doing so is
not required unless the M-file contains a nested function.
Functions normally return when the end of the function is reached. Use a
return statement to force an early return
Example :
function [mean,stdev] = stat(x)
n = length(x);
mean = sum(x)/n;
stdev = sqrt(sum((x-mean).^2/n));
end
www.ppk.110mb.com
154. Arrays and Matrices
Array Operations
[ ] Array constructor
, Array row element separator
; Array column element separator
: Specify range of array elements
end Indicate last index of array
+ Addition or unary plus
- Subtraction or unary minus
.* Array multiplication
./ Array right division
. Array left division
.^ Array power
.‘ Array (nonconjugated) transpose
www.ppk.110mb.com
155. Entering Matrices
We can enter matrices into MATLAB in several different ways:
Enter an explicit list of elements.
Load matrices from external data files.
Generate matrices using built-in functions.
Create matrices with your own functions in M-files
Separate the elements of a row with blanks or commas.
Use a semicolon ; to indicate the end of each row.
Surround the entire list of elements with square brackets, [ ]
A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
A =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
www.ppk.110mb.com
156. sum, transpose, and diag (of Matrix)
1. sums of the columns of matrix A
Syntax - sum(A)
A =
8 1 6
3 5 7
4 9 2
>> sum(A)
ans =
15 15 15
www.ppk.110mb.com
157. sum, transpose, and diag (of Matrix)
2. Transpose of the matrix
The transpose operation is denoted by an apostrophe or single quote, '. It flips a
matrix about its main diagonal and it turns a row vector into a column
vector.
Syntax – A’
Example :
A =
8 1 6
3 5 7
4 9 2
>> A‘
ans =
8 3 4
1 5 9
6 7 2
www.ppk.110mb.com
158. sum, transpose, and diag (of Matrix)
3. Diagonal of a Matrix
Elements on the main diagonal of a matrix is obtained diag functions
Syntax – diag(A);
Example:
A =
8 1 6
3 5 7
4 9 2
>> diag(A)
ans =
8
5
2
www.ppk.110mb.com
The other diagonal, the so-called antidiagonal. MATLAB
does not have a ready-made function for it.
Use fliplr for flips a matrix from left to right then use diag
function
A =
8 1 6
3 5 7
4 9 2
>> diag(fliplr(A))
ans =
6
5
4
159. Subscripts of Matrix
The element in row i and column j of A is denoted by A(i,j).
For example, A(4,2) is the number in the fourth row and second column.
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
>> A(4,2)
ans =
14
www.ppk.110mb.com
160. The Colon Operator
The colon :,is one of the most important MATLAB operators. It occurs in
several different forms.
The expression 1:10
is a row vector containing the integers from 1 to 10, 1 2 3 4 5 6
7 8 9 10
To obtain nonunit spacing, specify an increment. For example
>> 10:.5:13
ans =
10.0000 10.5000 11.0000 11.5000 12.0000 12.5000 13.0000
www.ppk.110mb.com
161. Swap columns of a matrix
To swap columns of a matrix (rearrange the columns)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
>> B=A(:,[1 3 2 4])
B =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
www.ppk.110mb.com
162. Generating Matrices
MATLAB provides four functions that generate basic matrices.
1. zeros - All zeros
Z = zeros(2,4)
Z =
0 0 0 0
0 0 0 0
2. ones - All ones
y=ones(3,3)
y =
1 1 1
1 1 1
1 1 1
www.ppk.110mb.com
163. 3. rand- Uniformly distributed random elements
y=rand(3,3)
y =
0.4103 0.3529 0.1389
0.8936 0.8132 0.2028
0.0579 0.0099 0.1987
4. randn - Normally distributed random elements
y=randn(3,3)
y =
-0.0956 -1.3362 -0.6918
-0.8323 0.7143 0.8580
0.2944 1.6236 1.2540
www.ppk.110mb.com
164. Concatenation
Concatenation is the process of joining small matrices to make bigger ones. In fact,
you made your first matrix by concatenating its individual elements. The pair of
square brackets, [], is the concatenation operator
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
B =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
>> [A B]
ans =
16 2 3 13 16 3 2 13
5 11 10 8 5 10 11 8
9 7 6 12 9 6 7 12
4 14 15 1 4 15 14 1
www.ppk.110mb.com
165. Deleting Rows and Columns
You can delete rows and columns from a matrix using just a pair of square
brackets
A =
16 3 13
5 10 8
9 6 12
4 15 1
>> A(:,2)=[]
A =
16 13
5 8
9 12
4 1
www.ppk.110mb.com
166. Adding and Subtracting Matrices
Addition and subtraction of matrices is defined just as it is for arrays,
element-by-element
x =
1 2 3
3 4 5
4 5 6
y =
11 33 44
44 55 66
77 88 99
x+y
12 35 47
47 59 71
81 93 105
www.ppk.110mb.com
x =
1 2 3
3 4 5
4 5 6
y =
11 33 44
44 55 66
77 88 99
y-x =
10 31 41
41 51 61
73 83 93
167. Multiplying Matrices
The matrix product C = AB is defined when the column dimension of A is
equal to the row dimension of B, or when one of them is a scalar. If A is m-
by-p and B is p-by-n, their product C is m-by-n
x =
1 2 3
3 4 5
4 5 6
y =
11 33 44
44 55 66
77 88 99
x*y =
330 407 473
594 759 891
726 935 1100
www.ppk.110mb.com
168. The Identity Matrix
Generally accepted mathematical notation uses the capital letter ‘I ‘to denote
identity matrices, matrices of various sizes with ones on the main diagonal
and zeros elsewhere.
I =eye(4)
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
www.ppk.110mb.com
169. Matrix Powers
If A is a square matrix and p is a positive integer, then A^p effectively
multiplies A by itself p-1 times.
A =
1 1 1
1 2 3
1 3 6
X = A^2
X =
3 6 10
6 14 25
10 25 46
www.ppk.110mb.com
Element-by-Element Powers
The .^ operator produces element-by-element powers.
For example, X = A.^2
A =
1 1 1
1 4 9
1 9 36
170. Eigenvalues
An eigenvalue and eigenvector of a square matrix A are a scalar λ and a nonzero
vector v that satisfy,
Av= λv
p =
1 2 3
4 5 6
7 8 9
>> [v,d]=eig(p)
v =
-0.2320 -0.7858 0.4082
-0.5253 -0.0868 -0.8165
-0.8187 0.6123 0.4082
d =
16.1168 0 0
0 -1.1168 0
0 0 -0.0000 www.ppk.110mb.com
171. Inverse of a Matrix
p =
1 2 3
4 5 6
7 8 0
>> inv(p)
ans =
-1.7778 0.8889 -0.1111
1.5556 -0.7778 0.2222
-0.1111 0.2222 -0.1111
www.ppk.110mb.com
172. Matrix Indexing
We select elements in a matrix just as we did for vectors, but now we need
two indices.The element of row i and column j of the matrix A is denoted
by A(i,j).
p =
1 2 3
4 5 6
7 8 0
>> p(3,1)
= 7
>> p(2,3)
= 6
www.ppk.110mb.com
173. Sub Matrix
The colon operator can also be used to pick out a certain row or column.
For example, the statement A(m:n,k:l) specifies rows m to n and column k
to l. Subscript expressions refer to portions of a matrix.
P =
1 3 4
5 4 3
5 6 7
>> P(2,:)
=
5 4 3
www.ppk.110mb.com
P =
1 3 4
5 4 3
5 6 7
>> P(:,2:3)
=
3 4
4 3
6 7
Creating a sub Matrix
P =
1 3 4
5 4 3
5 6 7
>> Q = P([2 3],[1 2])
Q =
5 4
5 6
174. Linear Algebra
Informally, the terms matrix and array are often used interchangeably. More precisely, a
matrix is a two-dimensional numeric array that represents a linear transformation.
The mathematical operations defined on matrices are the subject of linear algebra.
That are - Matrix analysis, linear equations, eigenvalues, singular values, logarithms,
exponentials, factorization
Matrix Operations
Cross and dot products, transpose
Linear Equations
Solve linear systems, least squares
Matrix Decomposition
Cholesky, LU, and QR factorizations, diagonal forms, singular value decomposition
Eigenvalues and Singular Values
Eigenvalues, eigenvectors, Schur decomposition, Hessenburg matrices, etc.
Matrix Analysis
Norm, rank, determinant, condition
Matrix Functions
Logarithms, exponentials, roots, other functions
www.ppk.110mb.com
175. Curve Fitting
Every system can be expressed with some equations. In
some cases, it is required to express a set of
observations by an equation of ‘best fit’.
Suppose we are given a data in terms of two variables
‘x’ and ‘y’. The problem of finding an analytic
expression of the form y=f(x) which fits the given
data is called ‘curve fitting’.
www.ppk.110mb.com
176. Reasons and purposes for fitting data
There can be different reasons and purposes for fitting data, including
• Getting certain features out of a set of data, e. g. finding a maximum or an
inflection point.
• Producing “nice” figures, i. e. plotting curves as guide for the eye.
• Describing data by a simpler physical principle, the fit will then yield the
parameters in the corresponding physical formula.
• Finding a lookup formula for a dependance between different physical
properties.
Fitting means to find a mathematical description for data. This
mathematical description should be “as close as possible” to the data.
Obviously one has to define in a mathematical way what is meant with “as
close as possible”. Commonly the root mean squared error is used as a
measure for the deviation. To “fit” then means to find a minimum for the
root mean squared error
177. Types of Fitting Methods with Matlab
Polynomial Fits - The simplest sort of fit functions are polynomials
MATLAB provides the function polyfit. In the simplest form, you call it for your data vectors
x and y through P = polyfit(x,y,n);
Parameter-Linear Fits - Similar to polynomial fits are so-called parameter-linear fits, i. e.
fits to an arbitrary function with the only restriction that this function is linear in the fit
parameters
There is no dedicated fit function for this sort of parameter-linear fits in MATLAB. However,
MATLAB knows how to solve a system of linear equations.Given such a system of linear
equations Az = b
where A is the matrix of the coefficients, z is the vector of the variables and b is the right
hand side vector of the equations, MATLAB solves this system using the function mldivide
(matrix left divide). This function can be abbreviated by ‘’. The solution vector then is, z =
mldivide(A,b);
Arbitrary Fit Functions Sometimes more complicated fit problems can be transformed to
parameter-linear fits. If this is not possible, one has to use arbitrary fit functions which are no
longer linear in the fit parameters. These generalized fit problems have to be solved using
optimization algorithms
To search for the minimum of an arbitrary function, MATLAB provides the function
fminsearch.
178. Curve Fitting Tool
With the Curve Fitting Tool, you can visually explore data and fits as scatter plots,
graphically evaluate the goodness of fit using residuals and prediction bounds, and
access graphical user interfaces (GUIs) for importing and fitting data, and for
plotting and analyzing fits to the data.
By clicking the Data, Fitting, Exclude, Plotting, or Analysis buttons, you can launch the
associated GUIs
Data GUI - Import, preview, name, and delete data sets. Smooth noisy data.
Fitting GUI –
(1)-Fit data using a library or custom equation, a smoothing spline, or
an interpolant. (2)-Examine and compare the fit results including fitted coefficient
values and goodness of fit statistics. (3)-Keep track of all the fits and associated data
sets for the current session.
Exclude GUI - Mark data to be excluded from a fit.
View the exclusion rule.
Plotting GUI - Control which data sets and fits are displayed in the Curve Fitting
Tool.
Analysis GUI - Evaluate (interpolate or extrapolate), differentiate, or integrate a fit.
Plot the analysis results and the data set.
www.ppk.110mb.com
179. Data Analysis with MATLAB
MATLAB Has Many Capabilities for Data Analysis
Preprocessing
–Scaling and averaging
–Interpolating and decimating
–Clipping and thresholding
–Extracting sections of data
–Smoothing and filtering
Applying numerical and mathematical operations
–Correlation, basic statistics, and curve fitting
–Fourier analysis and filtering
–Matrix analysis
–1-D peak, valley, and zero finding
–Differential equation solvers
www.ppk.110mb.com
181. Workflow for Data Analysis in MATLAB
•Access
–Data files - in all kinds of formats
–Software - by calling out to other languages/applications
–Hardware - using the Data Acquisition Toolbox, e.g.
•Pre-process… Analyze… Visualize…
•Share
–Reporting (MS Office, e.g.) - can do this with touch of a button
–Documentation for the Web in HTML
–Images in many different formats
–Outputs for design
–Deployment as a backend to a Web app
–Deployment as a GUI app to be used within MATLAB
www.ppk.110mb.com