# Loren on the Art of MATLAB

## From Symbolic Differential Equations to Their Numeric Solution

Once more, I am pleased to introduce guest blogger Kai Gehrs. Kai has been a Software Engineer at MathWorks for the past five years mainly working on features for the Symbolic Math Toolbox. He has a background in mathematics and computer science and already contributed to my blog in the past.

### Contents

In the article ODEs, from Symbolic to Numeric Code, Loren demonstrated how you can

• Compute a symbolic solution of an ordinary differential equation (ODE) using dsolve
• Convert the symbolic solution to a MATLAB function handle using matlabFunction
• Plot the solution using MATLAB's plot.

In this article, we consider a slightly different scenario. Suppose that we have defined an ODE. First, we try to solve it symbolically. But we find that the symbolic ODE solver cannot find a closed form solution (something which is likely to happen, because only particular classes of ODEs can be solved in closed symbolic form).

Since we cannot solve the ODE symbolically, we must switch to a numeric ODE solver. But numeric solvers require a particular form and type of arguments, which often differ from the arguments of a symbolic solver. Symbolic solvers require a scalar symbolic (= "textbook-like") representation of an ODE. Numeric solvers usually require them to be transformed to a coupled first-order system.

This article demonstrates the following workflow of transforming a symbolic representation of an ODE to a form accepted by the MATLAB numeric ODE solver ode45.

• Define an ODE in a symbolic form using symbolic functions
• Convert it to a coupled first-order system using odeToVectorField
• Create a function handle for the coupled first-order system using matlabFunction
• Solve the differential equation numerically using the MATLAB numeric ODE solver ode45
• Plot the solution using plot.

#### Defining a Differential Equation in Symbolic Form

We start with the second-order non-linear ODE with two given initial values:

$$y'' = (y - y^2) \cdot y' - y, \qquad y = y(t), \qquad y(0) = 2, \qquad y'(0) = 0.$$

We define it in a symbolic form using a symbolic function symfun y(t):

syms y(t);
ode = diff(y,2) == (y-y^2)*diff(y) - y;


When trying to compute a solution of this ODE using dsolve, we see that the symbolic ODE solver does not find an explicit closed form solution:

dsolve(ode)

Warning: Explicit solution could not be found.
ans =
[ empty sym ]


Adding the initial values does not help:

Dy = diff(y); dsolve(ode,y(0) == 2,Dy(0) == 0)

Warning: Explicit solution could not be found.
ans =
[ empty sym ]


So we must use a numeric ODE solver to be able to plot the solution. But before we can convert the symbolic form of the ODE to a function handle accepted by ode45, we must convert the scalar form of the ODE to a coupled first-order ODE system.

#### From Scalar ODE to Coupled First-Order System

The Symbolic Math Toolbox function odeToVectorField converts a scalar ODE to a first-order ODE system:

V = odeToVectorField(ode)

V =
Y[2]
- (Y[1]^2 - Y[1])*Y[2] - Y[1]


For details about the algorithm used to convert a general n-th order scalar ODE to a first-order coupled ODE system, see the odeToVectorField documentation page.

The next step is to convert the system representation V of the ODE to a function handle accepted by ode45.

#### From Coupled First-Order System to Function Handle Representation

To convert the expression V to a MATLAB function handle we use matlabFunction:

F = matlabFunction(V,'vars',{'t','Y'})

F =
@(t,Y)[Y(2);-(Y(1).^2-Y(1)).*Y(2)-Y(1)]


We are almost done. We only need to call the numeric ODE solver ode45 for the function handle F, and then plot the result.

#### From Function Handle Representation to Numeric Solution

Now we solve the differential equation converted to the function handle F:

sol = ode45(F,[0 10],[2 0]);


Here, [0 10] lets us compute the numerical solution on the interval from 0 to 10. Another additional parameter, [2 0], corresponds to the initial values: $y(0) = 2$ and $y'(0) = 0$.

Before plotting the solution, we use linspace to create 100 points in the interval [0,10] and deval to evaluate the solution at each of these points:

x = linspace(0,10,100);
y = deval(sol,x,1);


Now we plot the solution:

plot(x,y)


#### Have You Tried This Worklfow?

Have you tried using odeToVectorField and matlabFunction or creating symbolic functions with symfun? Let me know here. If you find Kai's article interesting, take a look at his other posts on my blog:

Get the MATLAB code

Published with MATLAB® R2013a

## Duality Between Function and Command Syntax

A long time ago, I covered the topic of the duality between command and function syntax.

### Contents

#### What is Command-Function Duality?

For calling functions with only literal string input values, i.e., strings delimited by the usual single quote ('), you can avoid the overhead of using parentheses and comma separators to invoke the function, especially if you want either no output or only one output. Let me show you an example.

#### Checking Directory Contents

Suppose I want to see the MATLAB code files in my directory beginning with the letter 'q'. Here are three ways to do such a query.

First way:

dir q*.m

qichen31.m  quadvec.m   quantum.m



Second Way:

dir('q*.m')

qichen31.m  quadvec.m   quantum.m



Third Way:

out = dir('q*.m')

out =
3x1 struct array with fields:
name
date
bytes
isdir
datenum


#### Discussion of Results

From these three methods, you can see that the first two give the same output, a list of the names of matching files. When using the command syntax (the first way), you can't store the output in a named variable. In this case, the decision was to print something out in a useful format, but not to place the information into a variable for further programmatic use.

The second result is equivalent to the first. You can see the duality looking at these two statements. The first and second are equivalent. Simply replace the space and following string (or strings) into a comma-separated list of the same string(s) inside parentheses. This means that the statement myfun A B c is equivalent myfun('A','B','c').

And now for the third statement. Clearly it is different than the first two. First, you can see that something is returned in the output variable out. Second, you can see that out is not simply a list of names, but a struct containing several fields with information, including name, date, etc.

#### Default MATLAB Behavior

MATLAB functions often return at least one output, even if the user does not supply an output variable. If the function does return an output when the user does not specify one, the result goes into a variable named ans.

#### Overriding Default Behavior

It is possible to override default behavior for your function outputs. To do so, we take advantage of the function nargout. This function allows us to query how many output variables the function is called with. In the case of the function dir, you can imagine the logic of the code goes something like this:

1. check nargout
2. if nargout is 0, get and print the list of matching files/directories
3. if nargout is greater than 0, collect the relevant directory information and place it into a structure

With the command form for calling a MATLAB function, the value for nargout is 0. Despite this, some functions are designed to return a value, though without a specified output, ans is created or updated.

Do you take advantage of command-function duality? In functions you create? At the MATLAB prompt or in application code your write? Let me know here.

Get the MATLAB code

Published with MATLAB® R2013a

## Recent Question about Speed with Subarray Calculations

Recently someone asked me to explain the speed behavior doing a calculation using a loop and array indexing vs. getting the subarray first.

### Contents

#### Example

Suppose I have a function of two inputs, the first input being the column (of a square array), the second, a scalar, and the output, a vector.

myfun = @(x,z) x'*x+z;


And even though this may be calculated in a fully vectorized manner, let's explore what happens when we work on subarrays from the array input.

I am now creating the input array x and the results output arrays for doing the calculation two ways, with an additional intermediate step in one of the methods.

n = 500;
x = randn(n,n);
result1 = zeros(n,1);
result2 = zeros(n,1);


#### First Method

Here we see and time the first method. In this one, we create a temporary array for x(:,k) n times through the outer loop.

tic
for k = 1:n
for z = 1:n
result1(z) = myfun(x(:,k), z);
end
result1 = result1+x(:,k);
end
runtime(1) = toc;


#### Second Method

In this method, we extract the column of interest first in the outer loop, and reuse that temporary array each time through the inner loop. Again we see and time the results.

tic
for k = 1:n
xt = x(:,k);
for z = 1:n
result2(z) = myfun(xt, z);
end
result2 = result2+x(:,k);
end
runtime(2) = toc;


#### Same Results?

First, let's make sure we get the same answer both ways. You can see that we do.

theSame = isequal(result1,result2)

theSame =
1


#### Compare Runtime

Next, let's compare the times. I want to remind you that doing timing from a script generally has more overhead than when the same code is run inside a function. We just want to see the relative behavior so we should get some insight from this exercise.

disp(['Run times are: ',num2str(runtime)])

Run times are: 2.3936      1.9558


#### What's Happening?

Here's what's going on. In the first method, we create a temporary variable n times through the outer loop, even though that array is a constant for a fixed column. In the second method, we extract the relevant column once, and reuse it n times through the inner loop.

Be thoughtful if you do play around with this. Depending on the details of your function, if the calculations you do each time are large compared to the time to extract a column vector, you may not see much difference between the two methods. However, if the calculations are sufficiently short in duration, then the repeated creation of the temporary variable could add a tremendous amount of overhead to the calculation. In general, you should not be worse off always capturing the temporary array the fewest number of times possible.

Have you noticed similar timing "puzzles" when analyzing one of your algorithms? I'd love to hear more here.

Get the MATLAB code

Published with MATLAB® R2013a

## Using Symbolic Math Toolbox to Compute Area Moments of Inertia

Once more I am pleased to introduce guest blogger Kai Gehrs. Kai has been a Software Engineer at MathWorks for the past five years working on the Symbolic Math Toolbox. He has a background in mathematics and computer science. He already contributed to my BLOG in the past writing about Using Symbolic Equations And Symbolic Functions In MATLAB as well as on approaches for Simplifying Symbolic Results.

### Contents

If you are interested in using MATLAB and the Symbolic Math Toolbox in teaching some basics in mechanical engineering, this might be of interest to you.

Computing area moments of inertia is an important task in mechanics. For example, area moments of inertia play a critical role in stress, dynamic, and stability analysis of structures. In this article, we use capabilities of the Symbolic Math Toolbox to compute area moments for cross sections of elliptical tubes.

We start with a basic case involving only numeric parameters, and then make the computations more general by introducing symbolic parameters.

All plots used in this article have been created in the MuPAD Notebook app. You can find the source code for these plots at the end of the article.

#### Basic Example: Cross Section of an Elliptical Tube

The following picture shows the cross section of an elliptical tube.

The following ellipses define outer and inner contours of the section:

• $y = \pm 2 \, \sqrt{1 - \frac{x^2}{9}}$ describe the outer contour line for $x \in [-3,3]$.
• $y = \pm \sqrt{1 - \frac{x^2}{4}}$ describe the inner contour line for $x \in [-2,2]$.

We will compute the area moment of inertia of this section with respect to the $x$-axis.

#### Area Moment Of Inertia

The moment of inertia of an area $A$ with respect to the $x$-axis is defined in terms of the double integral

$$I_x = {\int \int}_A y^2\, \mathrm{d}A.$$

You can find this definition on Wikipedia.

#### Math Behind This Example

In our example, the area $A$ is the hatched area shown in the previous plot. Taking advantage of the symmetry of the section with respect to both the $x$- and $y$-axes, we can restrict our computations to the first quadrant of the $x-y$-plane.

To compute the necessary double integral over the hatched area, we divide this area into two separate areas $A1$ and $A2$.

To compute the final area moment of inertia about the x-axis, we multiply the sum of the double integrals over $A_1$ and $A_2$ by four.

$$I_x = {\int\int}_A y^2 \, \mathrm dA = 4 \cdot \Big({\int\int}_{A_1} y^2 \, \mathrm dA_1 + {\int\int}_{A_2} y^2 \, \mathrm dA_2\Big).$$

Now, we only need to compute these two double integrals. The mathematical theory behind multi-dimensional integration tells us that we can rewrite each of these double integrals in terms of two integrals:

$$I_1 = {\int\int}_{A_1} y^2 \, \mathrm dA_1 = \int_0^2 \int_{\sqrt{1 - \frac{x^2}{4}}}^{2 \, \sqrt{1 - \frac{x^2}{9}}} y^2 \, \mathrm dy \, \mathrm dx,$$

$$I_2 = {\int\int}_{A_2} y^2 \, \mathrm dA_2 = \int_2^3 \int_{0}^{2 \, \sqrt{1 - \frac{x^2}{9}}} y^2\, \mathrm dy\, \mathrm dx.$$

The int function from the Symbolic Math Toolbox can compute these integrals.

#### Symbolic Integration

We define $x$ and $y$ as symbolic variables:

syms x y;


We start computing the inner integral $\int_{\sqrt{1 - \frac{x^2}{4}}}^{2 \, \sqrt{1 - \frac{x^2}{9}}} y^2 \, \mathrm dy$ of $I_1$:

innerI1 = int(y^2, y, sqrt(1-x^2/4), 2*sqrt(1-x^2/9))

innerI1 =
(8*(9 - x^2)^(3/2))/81 - (4 - x^2)^(3/2)/24


Next, we integrate innerI1 with respect to $x$ from $0$ to $2$. This provides $I_1$:

I1 = int(innerI1, x, 0, 2)

I1 =
3*asin(2/3) - pi/8 + (74*5^(1/2))/81


We use the same strategy to compute $I_2$. First, we compute the inner integral $\int_{0}^{2 \, \sqrt{1 - \frac{x^2}{9}}} y^2\, \mathrm dy$. Then, we integrate the resulting expression with respect to $x$ from $2$ to $3$:

I2 = int(int(y^2, y, 0, 2*sqrt(1-x^2/9)), x, 2, 3);


Hence, the area moment of inertia of the elliptical tube with respect to the $x$-axis is

Ix = 4 * (I1 + I2)

Ix =
(11*pi)/2


We can approximate the result numerically by using the vpa function. For example, we approximate the result using 5 significant (nonzero) digits:

vpa(Ix, 5)

ans =
17.279


#### Advanced Example: Cross Section of an Elliptical Tube Defined by Symbolic Parameters

We can use a numerical integrator, such as MATLAB's integral2, to compute the area moment of inertia in the previous example. A numerical integrator might return slightly less accurate results, but other than that there is not much benefit from using symbolic integration there.

But what if we consider the cross section of a more general elliptical tube whose shape is defined by arbitrary symbolic parameters?

For example, we want to compute the area moment of inertia of this elliptical tube.

Its contour lines are still ellipses, but they are defined by the symbolic parameters $r_1$, $r_2$, $R_1$ and $R_2$:

• $y = \pm R_2 \, \sqrt{1 - \frac{x^2}{R_1^2}}$ describe the outer contour line for $x \in [-R_1,R_1]$.
• $y = \pm r_2 \, \sqrt{1 - \frac{x^2}{r_1^2}}$ describe the inner contour line for $x \in [-r_1,r_1]$.

Now we need to compute these integrals:

$$I_1 = {\int\int}_{A_1} y^2 \, \mathrm dA_1 = \int_0^{r_1} \int_{r_2 \, \sqrt{1 - \frac{x^2}{r_1^2}}}^{R_2 \, \sqrt{1 - \frac{x^2}{R_1^2}}} y^2 \, \mathrm dy \, \mathrm dx,$$

$$I_2 = {\int\int}_{A_2} y^2 \, \mathrm dA_2 = \int_{r_1}^{R_1} \int_{0}^{R_2 \, \sqrt{1 - \frac{x^2}{R_1^2}}} y^2\, \mathrm dy\, \mathrm dx.$$

Although the situation is more complicated now, we can still use the same strategy as above, using symbolic variables instead of numbers. Nevertheless, we need to add one more step: specify relationships between symbolic parameters. This is because the variables $r_1$, $r_2$, $R_1$, and $R_2$ can be any complex number, unless we explicitly restrict their values. For example, the system does not know if these variables are positive or negative, if $r_1 < R_1$ or otherwise. In this example, we want to specify that $r_1>0$, $r_2>0$, $R_1>r_1$, and $R_2>r_2$. In the Symbolic Math Toolbox, such restrictions are called assumptions on variables. They can be set by using the assume and assumeAlso functions:

syms x y r1 r2 R1 R2;
assume(r1 > 0);
assume(r2 > 0);
assumeAlso(r1 < R1);
assumeAlso(r2 < R2);
I1 = int(int(y^2, y, r2*sqrt(1-x^2/r1^2), R2*sqrt(1-x^2/R1^2)), x, 0, r1);
I2 = int(int(y^2, y, 0, R2*sqrt(1-x^2/R1^2)), x, r1, R1);
Ixgeneral = 4 * (I1 + I2);
pretty(Ixgeneral)


/          4     / r1 \ \         /                     4     / r1 \ \
|      3 R1  asin| -- | |         |             4   3 R1  asin| -- | |
3 |                \ R1 / |       3 |      3 pi R1              \ R1 / |
4 R2  | #1 + ---------------- |   4 R2  | #1 - -------- + ---------------- |
\             8         /         \         16             8         /
------------------------------- - ------------------------------------------
3                                      3
3 R1                                   3 R1

3
pi r1 r2
- ---------
4

where

/     2        3 \
| 5 R1  r1   r1  |    2     2 1/2
#1 == | -------- - --- | (R1  - r1 )
\    8        4  /


Now, let's substitute our symbolic parameters with the same values that we had in the first example. Do we get the same result? Let's double-check: when substituting $r_1=2,r_2,=1,R_1=3,R_2=2$ in Ixgeneral, do we get the same result for Ix as obtained for the section initially considered?

As expected, the general solution Ixgeneral reduces to the specific solution Ix when we substitute our original dimensions:

vpa(subs(Ixgeneral, [r1, R1, r2, R2],[2, 3, 1, 2]), 5)

ans =
17.279


Note that it is essential to set the assumptions on $r_1$, $r_2$, $R_1$ and $R_2$. By default, the Symbolic Math Toolbox assumes that all variables including symbolic parameters are arbitrary complex numbers. This makes computing integrals much more complicated and time-consuming. For example, try computing Ixgeneral without setting the assumptions on $r_1$, $r_2$, $R_1$ and $R_2$. In general, it can be impossible to even get the result without any additional assumptions.

To generate the graphics shown in this article, use MuPAD Notebook app. Note that the code in this section does not run in the MATLAB Command Window.

To open the MuPAD Notebook app:

1. On the MATLAB Toolstrip, click the Apps tab.
2. On the Apps tab, click the down arrow at the end of the Apps section.
3. Under Math, Statistics and Optimization, click the MuPAD Notebook button.

Alternatively, type mupad in the MATLAB Command Window.

Paste the following commands to a MuPAD notebook to obtain the four graphics used above:

Ellipse:= (x,a,b) -> sqrt(b^2*(1-x^2/a^2)):
f1 := plot::Function2d(Ellipse(x,2,1), x = -3..3):
f2 := plot::Function2d(Ellipse(x,3,2), x = -3..3):
f3 := plot::Function2d(Ellipse(x,3,2), x = -3..-2):
f4 := plot::Function2d(Ellipse(x,3,2), x = 2..3):
f5 := plot::Function2d(-Ellipse(x,2,1), x = -3..3):
f6 := plot::Function2d(-Ellipse(x,3,2), x = -3..3):
f7 := plot::Function2d(-Ellipse(x,3,2), x = -3..-2):
f8 := plot::Function2d(-Ellipse(x,3,2), x = 2..3):
f9 := plot::Function2d(Ellipse(x,2,1), x = 0..2, VerticalAsymptotesVisible = FALSE):
f10 := plot::Function2d(Ellipse(x,3,2), x = 0..3, VerticalAsymptotesVisible = FALSE):
f11 := plot::Function2d(Ellipse(x,3,2), x = 2..3, VerticalAsymptotesVisible = FALSE):
plot(plot::Hatch(f1,f2),plot::Hatch(f3),plot::Hatch(f4),f1,f2,
plot::Hatch(f5,f6),plot::Hatch(f7),plot::Hatch(f8),f5,f6,
Scaling = Constrained,
GridVisible = TRUE,
VerticalAsymptotesVisible = FALSE,
Height = 120, Width = 200,
Header = "Cross section of elliptical tube (x-y-plane)"):
plot(plot::Hatch(f9,f10),plot::Hatch(f11),f9,f10,
Scaling = Constrained,
GridVisible = TRUE,
Height = 120, Width = 200,
Header = "Restriction to first quadrant (x-y-plane)"):
plot(plot::Hatch(f9,f10,Color=RGB::Magenta),plot::Hatch(f11,Color = RGB::Green),f9,f10,
Scaling=Constrained,
GridVisible = TRUE,
plot::Text2d("A1",[1.0,1.25]),
plot::Text2d("A2",[2.5,0.25]),
Height = 120, Width = 200,
Header = "Integration areas"):
plot(plot::Hatch(f1,f2),plot::Hatch(f3),plot::Hatch(f4),f1,f2,
plot::Hatch(f5,f6),plot::Hatch(f7),plot::Hatch(f8),f5,f6,
plot::Text2d("r1",[1.8,0.05]),
plot::Text2d("r2",[0.05,0.85]),
plot::Text2d("R1",[2.74,0.05]),
plot::Text2d("R2",[0.05,1.84]),
Scaling = Constrained,
GridVisible = TRUE,
VerticalAsymptotesVisible = FALSE,
XTicksLabelsVisible = FALSE,
YTicksLabelsVisible = FALSE,
ViewingBox = [-3.5..3.5,-2.5..2.5],
Height = 120, Width = 200,
Header = "Cross section of elliptical tube (more general situation)"):

#### Have You Tried Symbolic Math Toolbox?

Have you used the Symbolic Math Toolbox in computations related to mechanics? Let me know here.

Get the MATLAB code

Published with MATLAB® R2013a

## MATLAB to FPGA using HDL Coder(TM)

It's my pleasure to introduce guest blogger Kiran Kintali. Kiran is the product development lead for HDL Coder at MathWorks. In this post, Kiran introduces a new capability in HDL Coder™ that generates synthesizable VHDL/Verilog code directly from MATLAB and highlights some of the key features of this new MATLAB based workflow.

### Contents

#### Introduction to HDL Code Generation from MATLAB

If you are using MATLAB to model digital signal processing (DSP) or video and image processing algorithms that eventually end up in FPGAs or ASICs, read on...

FPGAs provide a good compromise between general purpose processors (GPPs) and application specific integrated circuits (ASICs). GPPs are fully programmable but are less efficient in terms of power and performance; ASICs implement dedicated functionality and show the best power and performance characteristics, but require extremely expensive design validation and implementation cycles. FPGAs are also used for prototyping in ASIC workflows for hardware verification and early software development.

Due to the order of magnitude performance improvement when running high-throughput, high-performance applications, algorithm designers are increasingly using FPGAs to prototype and validate their innovations instead of using traditional processors. However, many of the algorithms are implemented in MATLAB due to the simple-to-use programming model and rich analysis and visualization capabilities. When targeting FPGAs or ASICs these MATLAB algorithms have to be manually translated to HDL.

For many algorithm developers who are well-versed with software programming paradigms, mastering the FPGA design workflow is a challenge. Unlike software algorithm development, hardware development requires them to think parallel. Other obstacles include: learning the VHDL or Verilog language, mastering IDEs from FPGA vendors, and understanding esoteric terms like "multi-cycle path" and "delay balancing".

In this post, I describe an easier path from MATLAB to FPGAs. I will show how you can automatically generate HDL code from your MATLAB algorithm, implement the HDL code on an FPGA, and use MATLAB to verify your HDL code.

#### MATLAB to Hardware Workflow

The process of translating MATLAB designs to hardware consists of the following steps:

1. Model your algorithm in MATLAB - use MATLAB to simulate, debug, and iteratively test and optimize the design.
2. Generate HDL code - automatically create HDL code for FPGA prototyping.
3. Verify HDL code - reuse your MATLAB test bench to verify the generated HDL code.
4. Create and verify FPGA prototype - implement and verify your design on FPGAs.

There are some unique challenges in translating MATLAB to hardware. MATLAB code is procedural and can be highly abstract; it can use floating-point data and has no notion of time. Complex loops can be inferred from matrix operations and toolbox functions.

Implementing MATLAB code in hardware involves:

• Converting floating-point MATLAB code to fixed-point MATLAB code with optimized bit widths suitable for efficient hardware generation.
• Identifying and mapping procedural constructs to concurrent area- and speed-optimized hardware operations.
• Introducing the concept of time by adding clocks and clock rates to schedule the operations in hardware.
• Creating resource-shared architectures to implement expensive operators like multipliers and for-loop bodies.
• Mapping large persistent arrays to block RAM in hardware

HDL Coder™ simplifies the above tasks though workflow automation.

#### Example MATLAB Algorithm

Let’s take a MATLAB function implementing histogram equalization and go through this workflow. This algorithm, implemented in MATLAB, enhances image contrast by transforming the values in an intensity image so that the histogram of the output image is approximately flat.

type mlhdlc_heq.m

% Histogram Equalization Algorithm
function [pixel_out] = mlhdlc_heq(x_in, y_in, pixel_in, width, height)

persistent histogram
persistent transferFunc
persistent histInd
persistent cumSum

if isempty(histogram)
histogram = zeros(1, 2^8);
transferFunc = zeros(1, 2^8);
histInd = 0;
cumSum = 0;
end

% Figure out indices based on where we are in the frame
if y_in < height && x_in < width % valid pixel data
histInd = pixel_in + 1;
elseif y_in == height && x_in == 0 % first column of height+1
histInd = 1;
elseif y_in >= height % vertical blanking period
histInd = min(histInd + 1, 2^8);
elseif y_in < height % horizontal blanking - do nothing
histInd = 1;
end

%Read histogram

%Read transfer function

%If valid part of frame add one to pixel bin and keep transfer func val
if y_in < height && x_in < width
transValWrite = transValRead; %Write back same value
cumSum = 0;
elseif y_in >= height %In blanking time index through all bins and reset to zero
histValWrite = 0;
cumSum = transValWrite;
else
end

%Write histogram
histogram(histInd) = histValWrite;

%Write transfer function
transferFunc(histInd) = transValWrite;

pixel_out = transValRead;


#### Example MATLAB Test Bench

Here is the test bench that verifies that the algorithm works with an example image. (Note that this testbench uses Image Processing Toolbox functions for reading the original image and plotting the transformed image after equalization.)

type mlhdlc_heq_tb.m

%% Test bench for Histogram Equalization Algorithm
clear mlhdlc_heq;
testFile = 'office.png';

% Get intensity part of color image
YCBCR = rgb2ycbcr(RGB);
imgOrig = YCBCR(:,:,1);

[height, width] = size(imgOrig);
imgOut = zeros(height,width);
hBlank = 20;
% make sure we have enough vertical blanking to filter the histogram
vBlank = ceil(2^14/(width+hBlank));

for frame = 1:2
disp(['working on frame: ', num2str(frame)]);
for y_in = 0:height+vBlank-1
%disp(['frame: ', num2str(frame), ' of 2, row: ', num2str(y_in)]);
for x_in = 0:width+hBlank-1
if x_in < width && y_in < height
pixel_in = double(imgOrig(y_in+1, x_in+1));
else
pixel_in = 0;
end

             [pixel_out] = mlhdlc_heq(x_in, y_in, pixel_in, width, height);
             if x_in < width && y_in < height
imgOut(y_in+1,x_in+1) = pixel_out;
end
end
end
end
% Make color image from equalized intensity image
% Rescale image
imgOut = double(imgOut);
imgOut(:) = imgOut/max(imgOut(:));
imgOut = uint8(imgOut*255);

YCBCR(:,:,1) = imgOut;
RGBOut = ycbcr2rgb(YCBCR);

figure(1)
subplot(2,2,1); imshow(RGB, []);
title('Original Image');
subplot(2,2,2); imshow(RGBOut, []);
title('Equalized Image');
subplot(2,2,3); hist(double(imgOrig(:)),2^14-1);
title('Histogram of original Image');
subplot(2,2,4); hist(double(imgOut(:)),2^14-1);
title('Histogram of equalized Image');


Let's simulate this algorithm to see the results.

mlhdlc_heq_tb

working on frame: 1
working on frame: 2


The HDL Workflow Advisor (see the snapshot below) helps automate the steps and provides a guided path from MATLAB to hardware. You can see the following key steps of the workflow in the left pane of the workflow advisor:

1. Fixed-Point Conversion
2. HDL Code Generation
3. HDL Verification
4. HDL Synthesis and Analysis

Let's look at each workflow step in detail.

Fixed-Point Conversion

Signal processing applications are typically implemented using floating-point operations in MATLAB. However, for power, cost, and performance reasons, these algorithms need to be converted to use fixed-point operations when targeting hardware. Fixed-point conversion can be very challenging and time-consuming, typically demanding 25 to 50 percent of the total design and implementation time. The automatic floating-point to fixed-point conversion workflow in HDL Coder™ can greatly simplify and accelerate this conversion process.

The floating-point to fixed-point conversion workflow consists of the following steps:

1. Verify that the floating-point design is compatible with code generation.
2. Propose fixed-point types based on computed ranges, either through the simulation of the testbench or through static analysis that propagates design ranges to compute derived ranges for all the variables.
3. Generate fixed-point MATLAB code by applying proposed fixed-point types.
4. Verify the generated fixed-point code and compare the numerical accuracy of the generated fixed-point code with the original floating point code.

Note that this step is optional. You can skip this step if your MATLAB design is already implemented in fixed-point.

HDL Code Generation

The HDL Code Generation step generates HDL code from the fixed-point MATLAB code. You can generate either VHDL or Verilog code that implements your MATLAB design. In addition to generating synthesizable HDL code, HDL Coder™ also generates various reports, including a traceability report that helps you navigate between your MATLAB code and the generated HDL code, and a resource utilization report that shows you, at the algorithm level, approximately what hardware resources are needed to implement the design, in terms of adders, multipliers, and RAMs.

During code generation, you can specify various optimization options to explore the design space without having to modify your algorithm. In the Design Space Exploration and Optimization Options section below, you can see how you can modify code generation options and optimize your design for speed or area.

HDL Verification

Standalone HDL test bench generation:

HDL Coder™ generates VHDL and Verilog test benches from your MATLAB scripts for rapid verification of generated HDL code. You can customize an HDL test bench using a variety of options that apply stimuli to the HDL code. You can also generate script files to automate the process of compiling and simulating your code in HDL simulators. These steps help to ensure the results of MATLAB simulation match the results of HDL simulation.

HDL Coder™ also works with HDL Verifier to automatically generate two types of cosimulation testbenches:

• HDL cosimulation-based verification works with Mentor Graphics® ModelSim® and QuestaSim®, where MATLAB and HDL simulation happen in lockstep.
• FPGA-in-the-Loop simulation allows you to run a MATLAB simulation with an FPGA board in strict synchronization. You can use MATLAB to feed real world data into your design on the FPGA, and ensure that the algorithm will behave as expected when implemented in hardware.

HDL Synthesis

Apart from the language-related challenges, programming for FPGAs requires the use of complex EDA tools. Generating a bitstream from the HDL design and programming the FPGA can be daunting tasks. HDL Coder™ provides automation here, by creating project files for Xilinx® and Altera® that are configured with the generated HDL code. You can use the workflow steps to synthesize the HDL code within the MATLAB environment, see the results of synthesis, and iterate on the MATLAB design to improve synthesis results.

#### Design Space Exploration and Optimization Options

HDL Coder™ provides the following optimizations to help you explore the design space trade-offs between area and speed. You can use these options to explore various architectures and trade-offs without having to manually rewrite your algorithm.

Speed Optimizations

• Pipelining : To improve the design’s clock frequency, HDL Coder enables you to insert pipeline registers in various locations within your design. For example, you can insert registers at the design inputs and outputs, and also at the output of a given MATLAB variable in your algorithm.
• Distributed Pipelining : HDL Coder also provides an optimization based on retiming to automatically move pipeline registers you have inserted to maximize clock frequency, by minimizing the delay through combinational paths in your design.

Area Optimizations

• RAM mapping: HDL Coder™ maps matrices to wires or registers in hardware. If persistent matrix variables are mapped to registers, they can take up a large amount of FPGA area. HDL Coder™ automatically maps persistent matrices to block RAM to improve area efficiency. The challenge in mapping MATLAB matrices to block RAM is that block RAM in hardware typically has a limited set of read and write ports. HDL Coder™ solves this problem by automatically partitioning and scheduling the matrix reads and writes to honor the block RAM’s port constraints, while still honoring the other control- and data-dependencies in the design.
• Resource sharing: This optimization identifies functionally equivalent multiplier operations in MATLAB code and shares them. You can control the amount of multiplier sharing in the design.
• Loop streaming: A MATLAB for-loop creates a FOR_GENERATE loop in VHDL. The body of the loop is replicated as many times in hardware as the number of loop iterations. This results in an inefficient use of area. The loop streaming optimization creates a single hardware instance of the loop body that is time-multiplexed across loop iterations.
• Constant multiplier optimization: This design level optimization converts constant multipliers into shift and add operations using canonical signed digit (CSD) techniques.

#### Best Practices

Now, let's look at few best practices related to writing MATLAB code when targeting FPGAs.

When writing a MATLAB design:

• Use the code generation subset of MATLAB supported for HDL code generation.
• Keep the top-level interface as simple as possible. The top-level function size, types, and complexity determine the interface of the chip implemented in hardware.
• Do not pass in a big chunk of parallel data into the design. Parallel data requires a large number of IO pins on the chip, and would probably not be synthesizable. In a typical image processing design, you should serialize the pixels as inputs and buffer them internally in the algorithm.

When writing a MATLAB test bench:

• Call the design from the testbench function.
• Exercise the design thoroughly. This is particularly important for floating-point to fixed-point conversion, where HDL Coder™ determines the ranges of the variables in the algorithm based on the values the testbench assigns to the variables. You can reuse this testbench to generate an HDL testbench for testing the generated hardware.
• Simulate the design with the testbench prior to code generation to make sure there are no simulation errors, and to make sure all the required files are on the path.

#### Conclusion

HDL Coder™ provides a seamless workflow when you want to implement your algorithm in an FPGA. In this post, I have shown you how to take an image processing algorithm written in MATLAB, convert it to fixed-point, generate HDL code, verify the generated HDL code using the test bench, and finally, synthesize the design and implement it in hardware.

We hope this brief introduction to the HDL Coder™ and MATLAB-to-HDL code generation, verification framework has shown how you can quickly get started on implementing your MATLAB designs and target FPGAs. Please let us know in the comments for this post how you might use this new functionality. Or, if you've already tried using HDL Coder™, let us know about your experiences here.

Get the MATLAB code

Published with MATLAB® R2013a

## New Datatype under Development for Possible MATLAB Release

There is a new datatype we are playing around with that we hope to make available in an upcoming release and we would like your input beforehand.

### Contents

#### New Datatype in Action

Let me show you the new datatype in action so you can first get a feel for it.

inputData = magic(3)

inputData =
8     1     6
3     5     7
4     9     2

outputValues = dis(inputData);


#### Let's Examine the Output

outputValues

Why are you asking?
4     2     3
1     9     6
8     7     5


Well, that's a bit strange, isn't it? I wonder what the relationship between inputData and outputValues is. What can we learn about outputValues?

whos outputValues

  Name              Size            Bytes  Class    Attributes

outputValues      1x1               248  dis



Well, it's a dis array. Let's look at it again.

outputValues

What's it matter to you?
5     6     9
4     3     2
7     8     1


Say what? Let's check it a few more times.

outputValues
outputValues
outputValues

Who wants to know?
6     3     9
5     8     7
4     2     1
Who wants to know?
5     2     9
1     4     8
7     6     3
Who are you to ask me that?
5     3     7
9     8     2
1     4     6


Hoping you get the double meaning here - the dis array not only mixes up the values of the input for display purposes, but also tries to gently *dis*respect you along the way.

Even though this is a silly class, I'll show you the code so you can see how simple it is to make such a class.

type dis

classdef dis
%dis dis is a class.
%   In fact, it's a declasse class.

properties
Data
end
properties (Access=protected)
Original
end

properties (Constant)
'What''s it matter to you?',...
'Who are you to ask me that?',...
'Who wants to know?',...
'What''s the big deal?'}
end

methods
function display(obj)
obj.Data(:) = obj.Data(randperm(numel(obj.Data)));
disp(obj.Data)
end
function obj = dis(in)
obj.Original = in;
obj.Data = reshape(in(randperm(numel(in))),size(in));
end
end

end



#### Should We Invest More Resources?

Of course, I could also add some numeric functions like plus to dis, but I didn't take the time, in case you didn't find this possible new MATLAB addition useful. So please share your thoughts with us here.

Get the MATLAB code

Published with MATLAB® R2013a

## Multiple Y Axes

We were musing here about how common it is to want more than two Y axes on a plot. Checking out the File Exchange, there seem to be several candidates, indicating that this is something at least some people find useful.

### Contents

#### Sample Plot

Here's a sample plot using plotyy that comes with MATLAB.

x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
plotyy(x,y1,x,y2,'plot');


#### List of Some Possibilities

In addition to plotyy in MATLAB, here's a list of some of the candidates from the File Exchange.

#### What are You Plotting with More Y Axes?

I am curious to know what kind of data or results you are plotting so that having multiple y-axes makes a compelling presentation. Let us know here.

Get the MATLAB code

Published with MATLAB® R2013a

## Using the MATLAB Unit Testing Infrastructure for Grading Assignments

Steven Lord, Andy Campbell, and David Hruska are members of the Quality Engineering group at MathWorks who are guest blogging today to introduce a new feature in R2013a, the MATLAB unit testing infrastructure. There are several submissions on the MATLAB Central File Exchange related to unit testing of MATLAB code. Blogger Steve Eddins wrote one highly rated example back in 2009. In release R2013a, MathWorks included in MATLAB itself a MATLAB implementation of the industry-standard xUnit testing framework.

If you're not a software developer, you may be wondering if this feature will be of any use to you. In this post, we will describe one way someone who may not consider themselves a software developer may be able to take advantage of this framework using the example of a professor grading students' homework submissions. That's not to say that the developers in the audience should move on to the next post; you can use these tools to test your own code just like a professor can use them to test code written by his or her students.

There is a great deal of functionality in this feature that we will not show here. For more information we refer you to the MATLAB Unit Testing Framework documentation.

### Contents

#### Background

In order to use this feature, you should be aware of how to define simple MATLAB classes in classdef files, how to define a class that inherits from another, and how to specify attributes for methods and properties of those classes. The object-oriented programming documentation describes these capabilities.

#### Problem Statement

As a professor in an introductory programming class, you want your students to write a program to compute Fibonacci numbers. The exact problem statement you give the students is:

Create a function "fib" that accepts a nonnegative integer n and returns
the nth Fibonacci number. The Fibonacci numbers are generated by this
relationship:
F(0) = 1
F(1) = 1
F(n) = F(n-1) + F(n-2) for integer n > 1
Your function should throw an error if n is not a nonnegative integer.

#### Basic Unit Test

The most basic MATLAB unit test is a MATLAB classdef class file that inherits from the matlab.unittest.TestCase class. Throughout the rest of this post we will add additional pieces to this basic framework to increase the capability of this test and will change its name to reflect its increased functionality.

dbtype basicTest.m

1     classdef basicTest < matlab.unittest.TestCase
2
3     end

test = basicTest

test =
basicTest with no properties.


#### Running a Test

To run the test, we can simply pass test to the run function. There are more advanced ways that make it easier to run a group of tests, but for our purposes (checking one student's answer at a time) this will be sufficient. When you move to checking multiple students' answers at a time, you can use run inside a for loop.

Since basicTest doesn't actually validate the output from the student's function, it doesn't take very long to execute.

results = run(test)

results =
0x0 TestResult array with properties:

Name
Passed
Failed
Incomplete
Duration
Totals:
0 Passed, 0 Failed, 0 Incomplete.
0 seconds testing time.


Let's say that a student named Thomas submitted a function fib.m as his solution to this assignment. Thomas's code is stored in a sub-folder named thomas. To set up our test to check Thomas's answer, we add the folder holding his code to the path.

addpath('thomas');
dbtype fib.m

1     function y = fib(n)
2     if n <= 1
3         y = 1;
4     else
5         y = fib(n-1)+fib(n-2);
6     end



#### Test that F(0) Equals 1

The basicTest is a valid test class, and we can run it, but it doesn't actually perform any validation of the student's test file. The methods that will perform that validation need to be written in a methods block that has the attribute Test specified.

The matlab.unittest.TestCase class includes qualification methods that you can use to test various qualities of the results returned by the student files. The qualification method that you will likely use most frequently is the verifyEqual method, which passes if the two values you pass into it are equal and reports a test failure if they are not.

The documentation for the matlab.unittest.TestCase class lists many other qualification methods that you can use to perform other types of validation, including testing the data type and size of the results; matching a string result to an expected string; testing that a given section of code throws a specific errors or issues a specific warning; and many more.

This simple test builds upon generalTest by adding a test method that checks that the student's function returns the value 1 when called with the input 0.

dbtype simpleTest.m

1     classdef simpleTest < matlab.unittest.TestCase
2         methods(Test)
3             function fibonacciOfZeroShouldBeOne(testCase)
4                 % Evaluate the student's function for n = 0
5                 result = fib(0);
6                 testCase.verifyEqual(result, 1);
7             end
8         end
9     end


Thomas's solution to the assignment satisfies this basic check. We can use the results returned from run to display the percentage of the tests that pass.

results = run(simpleTest)
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), '% Passed.']);

Running simpleTest
.
Done simpleTest
__________

results =
TestResult with properties:

Name: 'simpleTest/fibonacciOfZeroShouldBeOne'
Passed: 1
Failed: 0
Incomplete: 0
Duration: 0.0112
Totals:
1 Passed, 0 Failed, 0 Incomplete.
0.011168 seconds testing time.
100% Passed.


#### Test that F(pi) Throws an Error

Now that we have a basic positive test in place we can add in a test that checks the behavior of the student's function when passed a non-integer value (like n = pi) as input. The assignment stated that when called with a non-integer value, the student's function should error. Since the assignment doesn't require a specific error to be thrown, the test passes as long as fib(pi) throws any exception.

dbtype errorCaseTest.m

1     classdef errorCaseTest < matlab.unittest.TestCase
2         methods(Test)
3             function fibonacciOfZeroShouldBeOne(testCase)
4                 % Evaluate the student's function for n = 0
5                 result = fib(0);
6                 testCase.verifyEqual(result, 1);
7             end
8             function fibonacciOfNonintegerShouldError(testCase)
9                 testCase.verifyError(@()fib(pi), ?MException);
10            end
11        end
12    end


Thomas forgot to include a check for a non-integer valued input in his function, so our test should indicate that by reporting a failure.

results = run(errorCaseTest)
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), '% Passed.']);

Running errorCaseTest
.
================================================================================
Verification failed in errorCaseTest/fibonacciOfNonintegerShouldError.

---------------------
Framework Diagnostic:
---------------------
verifyError failed.
--> The function did not throw any exception.

Expected Exception Type:
MException

Evaluated Function:
@()fib(pi)

------------------
Stack Information:
------------------
In C:\Program Files\MATLAB\R2013a\toolbox\matlab\testframework\+matlab\+unittest\+qualifications\Verifiable.m (Verifiable.verifyError) at 637
In H:\Documents\LOREN\MyJob\Art of MATLAB\errorCaseTest.m (errorCaseTest.fibonacciOfNonintegerShouldError) at 9
================================================================================
.
Done errorCaseTest
__________

Failure Summary:

Name                                            Failed  Incomplete  Reason(s)
=============================================================================================
errorCaseTest/fibonacciOfNonintegerShouldError    X                 Failed by verification.

results =
1x2 TestResult array with properties:

Name
Passed
Failed
Incomplete
Duration
Totals:
1 Passed, 1 Failed, 0 Incomplete.
0.026224 seconds testing time.
50% Passed.


Another student, Benjamin, checked for a non-integer value in his code as you can see on line 2.

rmpath('thomas');
dbtype fib.m

1     function y = fib(n)
2     if (n ~= round(n)) || n < 0
3         error('N is not an integer!');
4     elseif n == 0 || n == 1
5         y = 1;
6     else
7         y = fib(n-1)+fib(n-2);
8     end


Benjamin's code passed both the test implemented in the fibonacciOfZeroShouldBeOne method (which we copied into errorCaseTest from simpleTest) and the new test case implemented in the fibonacciOfNonintegerShouldError method.

results = run(errorCaseTest)
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), '% Passed.']);

Running errorCaseTest
..
Done errorCaseTest
__________

results =
1x2 TestResult array with properties:

Name
Passed
Failed
Incomplete
Duration
Totals:
2 Passed, 0 Failed, 0 Incomplete.
0.010132 seconds testing time.
100% Passed.


#### Basic Test for Students, Advanced Tests for Instructor

The problem statement given earlier in this post is a plain text description of the homework assignment we assigned to the students. We can also state the problem for the students in code (if they're using release R2013a or later) by giving them a test file they can run just like simpleTest or errorCaseTest. They can directly use this "requirement test" to ensure their functions satisfy the requirements of the assignment.

dbtype studentTest.m

1     classdef studentTest < matlab.unittest.TestCase
2         methods(Test)
3             function fibonacciOfZeroShouldBeOne(testCase)
4                 % Evaluate the student's function for n = 0
5                 result = fib(0);
6                 testCase.verifyEqual(result, 1);
7             end
8             function fibonacciOfNonintegerShouldError(testCase)
9                 testCase.verifyError(@()fib(pi), ?MException);
10            end
11        end
12    end


In order for the student's code to pass the assignment, it will need to pass the test cases given in the studentTest unit test. However, we don't want to use studentTest as the only check of the student's code. If we did, the student could write their function to cover only the test cases in the student test file.

We could solve this problem by having two separate test files, one containing the student test cases and one containing additional test cases the instructor uses in the grading process. Can we avoid having to run both test files manually or duplicating the code from the student test cases in the instructor test? Yes!

To do so, we write an instructor test file to incorporate, through inheritance, the student test file. We can then add additional test cases to the instructor test file. When we run this test it should run three test cases; two inherited from studentTest, fibonacciOfZeroShouldBeOne and fibonacciOfNonintegerShouldError, and one from instructorTest itself, fibonacciOf5.

dbtype instructorTest.m

1     classdef instructorTest < studentTest
2         % Because the student test file is a matlab.unittest.TestCase and
3         % instructorTest inherits from it, instructorTest is also a
4         % matlab.unittest.TestCase.
5
6         methods(Test)
7             function fibonacciOf5(testCase)
8                 % Evaluate the student's function for n = 5
9                 result = fib(5);
10                testCase.verifyEqual(result, 8, 'Fibonacci(5) should be 8');
11            end
12        end
13    end


Let's look at Eric's test file that passes the studentTestFile test, but in which he completely forgot to implement the F(n) = F(n-1)+F(n-2) recursion step.

rmpath('benjamin');
dbtype fib.m

1     function y = fib(n)
2     if (n ~= round(n)) || n < 0
3         error('N is not an integer!');
4     end
5     y = 1;



It should pass the student unit test.

results = run(studentTest);
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), '% Passed.']);

Running studentTest
..
Done studentTest
__________

100% Passed.


It does NOT pass the instructor unit test because it fails one of the test cases.

results = run(instructorTest)
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), '% Passed.']);

Running instructorTest
..
================================================================================
Verification failed in instructorTest/fibonacciOf5.

----------------
Test Diagnostic:
----------------
Fibonacci(5) should be 8

---------------------
Framework Diagnostic:
---------------------
verifyEqual failed.
--> NumericComparator failed.
--> The values are not equal using "isequaln".

Actual Value:
1
Expected Value:
8

------------------
Stack Information:
------------------
In C:\Program Files\MATLAB\R2013a\toolbox\matlab\testframework\+matlab\+unittest\+qualifications\Verifiable.m (Verifiable.verifyEqual) at 411
In H:\Documents\LOREN\MyJob\Art of MATLAB\instructorTest.m (instructorTest.fibonacciOf5) at 10
================================================================================
.
Done instructorTest
__________

Failure Summary:

Name                         Failed  Incomplete  Reason(s)
==========================================================================
instructorTest/fibonacciOf5    X                 Failed by verification.

results =
1x3 TestResult array with properties:

Name
Passed
Failed
Incomplete
Duration
Totals:
2 Passed, 1 Failed, 0 Incomplete.
0.028906 seconds testing time.
66.6667% Passed.


Benjamin, whose code we tested above, wrote a correct solution to the homework problem.

rmpath('eric');

results = run(instructorTest)
percentPassed = 100 * nnz([results.Passed]) / numel(results);
disp([num2str(percentPassed), '% Passed.']);

rmpath('benjamin');

Running instructorTest
...
Done instructorTest
__________

results =
1x3 TestResult array with properties:

Name
Passed
Failed
Incomplete
Duration
Totals:
3 Passed, 0 Failed, 0 Incomplete.
0.015946 seconds testing time.
100% Passed.


#### Conclusion

In this post, we showed you the basics of using the new MATLAB unit testing infrastructure using homework grading as a use case.

We checked that the student's code worked (by returning the correct answer) for one valid value and worked (by throwing an error) for one invalid value. We also showed how you can use this infrastructure to provide an aid/check for the students that you can also use as part of your grading.

We hope this brief introduction to the unit testing framework has shown you how you can make use of this feature even if you don't consider yourself a software developer. Let us know in the comments for this post how you might use this new functionality. Or, if you've already tried using matlab.unittest, let us know about your experiences here.

Get the MATLAB code

Published with MATLAB® R2013a

## Major New Release at Chebfun – Two Dimensional Capabilities

Perhaps you've read about Chebfun before here or on Cleve''s blog. Chebfun allows you to do numerical computing with functions and not simply numbers. If not, you might want to investigate. If so, you may be very interested in new capabilities available.

### Contents

#### Major New Capability

Just recently, the Chebfun team released a major new capability on their site. While Chebfun is extremely useful, it was restricted to solving problems in one dimension. Now you may solve problems with two independent variables using Chebfun2! As before, their website includes code you can freely download and many interesting examples. The examples are well documented and easy to learn from. I will soon have time to explore Chebfun2 because of an irrational amount of airline time.

I also love how easy it is to install - you can do it from MATLAB. They kindly post the code right on the website so you can paste it into your running session.

#### Many Examples

They have many examples included in the software, and posted on their web site, using the publish command in MATLAB. The high-level examples are organized into these categories:

1. Approximation
2. Complex Analysis
3. Geometry
4. Optimization
5. Statistics
6. Rootfinding
7. Vector Calculus
8. Fun !

I hope with this breadth of examples, you are able to find ones interesting or relevant (or both) to you. Once you've gotten a chance to try out Chebfun2, I'd love to hear about your experiences. Post them here to share with us.

Get the MATLAB code

Published with MATLAB® R2012b

## Logical Indexing – Multiple Conditions

I've talked about logical indexing before in some of the linked posts, but recent work makes me want to show it off again. One of the nice things about logical indexing is that it is very easy and natural to combine the results of different conditions to select items based on multiple criteria.

### Contents

#### What is Logical Indexing?

Suppose I have an array of integers, not sorted, and want to find the ones that are less than a certain number. Here's how I can do it using the function find.

X = randperm(20)
target = 5;

X =
Columns 1 through 13
3     7     1    16    20    15    13     9    14     8    11    19    18
Columns 14 through 20
4    10     5     6    17    12     2

ind = find(X < target)

ind =
1     3    14    20


You can see that find returns the indices into the array X that have values less than the target. And we can use these to extract the values.

Xtarget = X(ind)

Xtarget =
3     1     4     2


Another way to accomplish the same outcome is to use the logical expression to directly perform the indexing operation. Here's what I mean.

logInd = X < target

logInd =
Columns 1 through 13
1     0     1     0     0     0     0     0     0     0     0     0     0
Columns 14 through 20
1     0     0     0     0     0     1


MATLAB returns an array that matches the elements of the array X, element-by-element holding 1s where the matching values in X are the desired values, and 0s otherwise. The array logInd is not an array of double numbers, but have the class logical.

whos logInd

  Name        Size            Bytes  Class      Attributes



I can now use this array to extract the desired values from X.

XtargetLogical = X(logInd)

XtargetLogical =
3     1     4     2


Both methods return the results.

isequal(Xtarget, XtargetLogical)

ans =
1


#### Compound conditions.

Let me create an anonymous function that returns true (logical(1)) for values that are even integers.

iseven = @(x) ~logical(rem(x,2))

iseven =
@(x)~logical(rem(x,2))


Test iseven.

iseven(1:5)

ans =
0     1     0     1     0


#### Find Values Meeting More Than One Condition

Now I would like to find the values in X that are less than target and are even. This is very natural to do with logical indexing. We have the pieces of code we need already.

compoundCondInd = (X < target) & iseven(X)

compoundCondInd =
Columns 1 through 13
0     0     0     0     0     0     0     0     0     0     0     0     0
Columns 14 through 20
1     0     0     0     0     0     1


We can see we found suitable values at locations 3 and 19. And we can extract those values next.

X(compoundCondInd)

ans =
4     2


#### Did You Notice?

Did you see how easy it is to combine multiple conditions? I simply look for each of condition, getting back logical arrays, and then compute a logical array where the two input arrays are both true (via &). I could, of course, calculate a compound condition where only either one or the other condition needs to be true using logical or (via |).

#### A Recent Application

I recently used this in the context of finding suspect data values. I had 2 arrays, hourly temperature and speed. The problem is that when the temperature gets near or below freezing, the speed sensor might freeze. But I didn't want to delete ALL the values below freezing. So I looked for data where the temperature was sufficiently low AND the speed was very low (which could potentially mean the sensor was frozen). That way, I did not need to discard all data at low temperatures.

#### Have You Used Compound Indexing?

Did you do it like I did, using logical expressions? Or did you use some other techniques? What were you trying to achieve with your compound indexing? Let me know here.

Get the MATLAB code

Published with MATLAB® R2012b

Loren Shure works on design of the MATLAB language at MathWorks. She writes here about once a week on MATLAB programming and related topics.

These postings are the author's and don't necessarily represent the opinions of MathWorks.