Robert Anderson
Xilinx

 

This paper is the first in a three-part series describing techniques and methods for using MATLAB as an executable specification for hardware development. Why use MATLAB as an executable specification for hardware when other options exist such as Simulink, C, or RTL? The answer is verification. Because when the application is signal processing, MATLAB offers a vastly superior environment for input vector generation and output waveform analysis.

Using MATLAB allows the algorithm developer to create a model that more accurately describes the characteristics of the final hardware implementation. This flow enables the algorithm developer to reduce design iterations, shorten development cycles, and assert more control over the hardware development process.

 

Link: xilinx_matlab

Most signal processing and communication projects nowadays at some point require translating MATLAB code into equivalent C code. Goals and requirements of the resulting C code can be diverse. Examples include:

 


While C code requirements vary widely, some translation pitfalls are common across all applications and teams. Many of these pitfalls derive from the fact that MATLAB is essentially an interpreted language. Consequently, it does not require a priori knowledge. I.e., MATLAB doesn’t know the type, shape, dimension or even the existence of any variable or function until execution.

Let us list some of the most common or bothersome pitfalls:

 

  • MATLAB indexes array elements starting with 1 whereas C indexing starts with 0
  • MATLAB is column major whereas C is row major. This means consecutive data in MATLAB are column elements whereas consecutive data in C are row elements.
  • MATLAB is inherently a vector-based representation. This can make the translation challenging. In particular:
    • You must replace the simplest vector operations with a loop construct
    • Operators (such as times ‘*’) in MATLAB perform different operations depending on the type of the operands
    • MATLAB includes very simple and powerful vector operations such as the concatenation “[]“and column “x(:)” operators or “end” construct, which can be quite hard to map to C

     

  • MATLAB supports “polymorphism” whereas C does not. I.e., you can write a generic function in MATLAB, which can process different types of input parameters. In C, each parameter has one given type, which cannot change.
  • MATLAB supports dynamic extensions and sizing of arrays, whereas C code requires storage to be allocated explicitly using malloc/free.
  • MATLAB draws on a rich set of libraries that are not available in C. Implementing such functions requires writing new code. Sometimes there are pre-exiting libraries and functions available for your target platform, but integrating them into your application can be problematic. In addition to running into licensing issues (such using GPL code for commercial application), interfacing with these libraries is non-trivial.
  • MATLAB supports reusing the same variable for different contents (different types). C does not, as each variable has one unique type.

As we will see, the process of writing C code from MATLAB is trickier than it sounds.

Preliminary step - What are my inputs?
When converting MATLAB to C, the first thing you need is a description of your function’s input parameters. This is because MATLAB, being an interpreted language, does not require declaration of data type for any variable.

Complicating matters, MATLAB variables have the following features not available in C

  • The ability to have a variable number of parameters 
  • MATLAB data types that have no C equivalent, such as “cell arrays”, a collection of heterogeneous types packed into slices of an array

Typically, information about input parameters can be found in comments embedded at the top of the MATLAB function, or in a report written by the MATLAB code implementer.

Conversion Examples
With the input parameters defined, we can now turn to the MATLAB code itself. To illustrate some basic issues with translating MATLAB to C, we will show three examples, which we will translate by hand.

Example 1 – Simple(?) MATLAB code
Let’s start with a simple example. The MATLAB code below take in a vector ‘x’, and returns all but the first two values, sorted in ascending order, that are greater than a given threshold.

In MATLAB, this is an easy feat:

 


We can run it on a simple case:

 


Even such a trivial example, which does not make use of any advanced matrix or mathematical features of MATLAB, presents a number of problems for the C implementer:

 


An example implementation, as written in syntactically correct C, is shown below (where the “my_sort” function still has to be implemented):

 


We have only scratched the surface, but clearly, there is nothing obvious about translating such simple MATLAB code into C.

Example 2: Polymorphism
MATLAB does not require knowing the type of the input parameters. This means that one single function can be called with different arguments. Moreover, the times operator ‘*’ in MATLAB can perform a cross-product, a norm or an element-by-element multiplication depending on the operands, as shown below.

 


In this case, the function “polymorph” performs two very different computations to compute ‘a’ and ‘b’:

  • for ‘a’, it computes the norm of the vector ‘x_complex_matrix’ which is +30.
  • for ‘b’, it computes the sum of the multiplication of ‘x_complex_matrix’ with a scalar (’x_real_scalar’). The result is 12 -6i

We can run this function in MATLAB:

 


When translating this behavior to C, you are likely to want to write two completely different functions for “polymorph’.

 


Here is an example of how this function would look like in C, assuming we know that the input matrix has 10 elements.

 


(Click to enlarge)

Example 3: Dealing with unintended array expansion
One of our favorite (and real-life) examples is the unintentional expansion of a pre-defined array in MATLAB.

The story goes like this: the MATLAB designer thinks that array ‘x’ is 14-elements long. He declares it to be that way and never worries about whether this is actually the case or not. The C implementer, taking his word for it, declares ‘x’ to be ‘double[14]‘.

After countless simulations and week-ends spent debugging the mismatches between the MATLAB code and the C code, it turns out x was actually 15-long (in some exceptional case) and that the C code was reading in incorrect values.

MATLAB, indeed, lets you write statements such as:

 


If N turns out to be 15 at some point, you are not going to get any hint: “x” is going to be automatically extended to 15 elements. Not so in C, with the consequences mentioned above.

 


Preview of a better way
All of the problems discussed can be addressed more generally with an automated approach. Therefore, in part 3, we will present an automatic way to convert MATLAB code to C with Catalytic MCS, showing how all pitfalls are dealt with automatically, and how such an approach also ensures easy debugging and synchronized M and C models. For example, MCS instantly points you to the culprit in the previous example when using its debug mode.

But before that, in part 2 we’ll look at how interface constraints play a role in the translation process and discuss the need for equivalent C libraries for MATLAB functions.

About the authors
Marc Barberis leads the applications group at Catalytic Inc. Prior to Catalytic, he held several positions in wireless design and system level simulation tools . His interests include physical layer for 3G and digital receiver algorithms. Marc holds a MS in EE from Ecole Nationale Superieure des Telecommunications de Paris. He can be reached at marc@catalyticinc.com.

Luc Semeria is product manager at Catalytic Inc. Prior to Catalytic, he held several positions at Synopsys Inc. His research interests include compilers, EDA tools, computer architecture, and DSP algorithms. Luc holds a Ph.D. in Electrical Engineering from Stanford University. He can be reached at luc@catalyticinc.com.

Related articles:

 

 

In the first part of this series, we showed how basic MATLAB operations can be translated into C code. This section focuses on translating more complex MATLAB functions or toolbox functions into C, and on integrating C algorithms derived from MATLAB into your application.

Implementing complex MATLAB functions
Of the many MATLAB functions used to develop algorithms, most do not have equivalents in the C language. For example, the C language does not have equivalents for basic MATLAB functions such as “find” (which automatically extracts elements from an array) or “sort” (which sorts array elements).

Some of these functions are fairly well known and can be found in C libraries or on the Internet. For example, it is easy to find sorting algorithms. Nevertheless, finding the most efficient implementation for MATLAB’s sort function can be quite an adventure, as noted in this article.

In addition, you may not be able to use the functions you find due to license restrictions. These include license restrictions on derivative work from copyrighted material (such as MATLAB files) or open-source (GPL) files. In such case, you may need to carefully and independently recode the algorithms by hand for your commercial application.

When you implement a MATLAB function in a language such as C, you may find it difficult to replicate MATLAB’s results. For example, image processing applications may use morphology functions such as “imresize” to resize an image. When implementing such functions, it is easy to end up with results that are a fraction of a pixel off from MATLAB’s results. (Even MATLAB 2006b and 2007a produce different results for the “imresize” function because they implement it differently). To replicate MATLAB’s results, you may need to recalibrate your algorithm in C. This might add significant delay to your project.

Some functions have implementations in both MATLAB and C. The standard math C library can be used to implement functions such as divide, sqrt, cos, sin, etc. in C when dealing with real scalar data. Things get more complicated once you start adding complex numbers and matrices into the mix.

For example, the operation “a/b” may be look like a simple divide operator in MATLAB.

When the operands are complex scalars, the operation is slightly more complicated in C:

 


If b is a matrix, “a/b” becomes a “matrix divide,” which is a lot more complicated to implement. A “matrix divide” requires solving a linear system of equations consisting of finding ‘x’ such that “a*x=b”. This is typically performed using complex matrix manipulations based on matrix QR decompositions. An example of this approach is shown in Implementing matrix inversions in fixed-point hardware.

Integrating with other functions and interface definition
When translating a MATLAB algorithm to C, you may be able to re-use existing code or leverage functions available in libraries. Your task then is to integrate the C code derived from your MATLAB algorithm with existing source code and libraries. To make this integration successful you need to make sure the interfaces of your different functions are compatible. In particular, you need to pay special attention to conventions on how complex and multi-dimensional variables are laid out in memory, when data are passed by references and by value, and whether indices start from 1 or 0.

Indices start with 1 in MATLAB and 0 in C
One difference between MATLAB and C is that MATLAB uses one-base indexing whereas C uses zero-base indexing. This means that the index of the first element of an array in C is 0, and is 1 in MATLAB.

You need to be aware of this when communicating index values between C and MATLAB functions, otherwise you may end up addressing elements that are off by one in your final C code.

 


Consecutive array elements are stored in columns in MATLAB and in rows in C
MATLAB use column-major order, which mean column elements are stored next to each other in memory. In contrast, C uses row-major order, which means that row elements are stored next to each other. (See Wikipedia for details on the two array layouts.) Array layout is critical for correctly passing arrays between C and MATLAB functions. It is also important when accessing a specific data element using a single subscript ((*a)[i] instead of a[i][j]), or for traversing an array without cache misses for good performance.

If your NxM MATLAB array is implemented as an NxM array in C, you need to watch out for single subscripts. In the example below, the 7th element of the array cst in MATLAB is cst(7) that stores the value “4″. The 7th element of the array cst in C is cst[7-1] that stores the value “7″. To access the value “4″ in the C code, you would need to access cst[4-1]. As a result, when arrays are addressed with single-subscript expressions, you might have to add some extra computation in order to access the right location within your array.

 


(Click to enlarge)

Some algorithms such as symmetrical filters do not depend on the orientation of the data, which means they produce the same outputs when traversing data row by row or column by column. In this case, it is not necessary to recompute single subscript expressions in your C code.

If you want the data in the C code to be located at the same positions as in MATLAB, your other option is to map the NxM array in MATLAB into a MxN array in C. In the example below, the 7th element of the array is cst(7) in MATLAB and cst_rot[7-1] in C and they both store the value “4″. This requires rotating the data when interfacing with other C code that expects data to be stored in row-major order. An example of this approach is shown here.

 


(Click to enlarge)

Rotating data into and out of your function requires extra memory and copying. In many cases, it is more efficient to translate MATLAB’s column-major code into a row-major C code.

Dealing with Complex numbers
Support for complex data is built into MATLAB. For example, the result of an FFT is simply stored into a variable “y=fft(x)”. The implementation of the complex data type itself is abstracted away from the programmer. In contrast, ANSI-C does not have a built-in data type for complex numbers. (Complex data support has been added as part of the C99 standard.)

Typically, there are two ways of implementing complex arrays:

  • Separate or split complex: the real part and imaginary part are stored into two separate arrays (e.g. separate a_real[0] and a_imag[0])
  • Interleaved: the real and imaginary parts of a given array element are stored next to each other in memory (e.g. interleaved a[0] for the real part and a[1] for the imaginary part)

Much like with row-major vs. column-major, the decision on which implementation to use depends on how data is accessed in the algorithm and most importantly on how data is communicated to external functions.

MATLAB stores real and imaginary parts in separate arrays. This makes calls to the “real” and “imag” functions trivial to implement. On the other hand, many programming environments (including C99, FORTRAN, etc) and common libraries (Intel MKL, LAPACK, BLAS, FFTW, etc.) make use of the interleaved complex data type.

Translating split complex data into interleaved complex data requires extra memory and copies. If your algorithm often calls functions that are only available with interleaved complex data, it is more efficient to translate MATLAB’s split complex arrays into interleaved complex arrays in C.

Passing arrays by reference
MATLAB programmers typically do not have to worry about whether data are passed by reference or by value. Internally, all arrays in MATLAB are kept as “references” as long as their values remain unchanged. A local copy of the array is created as soon as a value within the array changes, in order to prevent unexpected side-effects.

To replicate this semantics in C, you need to copy data explicitly. As an example, if an array is the input of a function, it may only be passed by reference if that array does not get modified inside of the function.

MATLAB doesn’t explicitly support parameter passing by reference. However, an implicit convention is to use the same parameter names for both the input and output of the function to perform “in-place operations,” as illustrated in this blog. In C code, this can be accomplished by passing a pointer to the input parameter.

Interfacing with C libraries
The considerations presented in the previous sections apply to library functions as well as to functions that you implement yourself. For example, FFTW, LAPACK or the Intel Math Kernel Library all implement complex data as interleaved data. Data in LAPACK are passed in column-major format. FFTW, on the other hand, supports both row- and column-major formats.

Most libraries have specific memory allocation requirements on what data must be pre-allocated before the function is called, and freed after the function returns. The LAPACK library has the special property that all input, output or intermediary arrays must be pre-allocated by the caller of the library function and passed by reference. This way no dynamic memory allocation happens within the function called.

Some libraries even use specific memory allocators. For example, the FFTW library defines its own “fftw_malloc” function to guarantee that the returned pointer obeys the alignment restrictions imposed by the FFTW algorithm implementation.

In addition to constraints on the interfaces, the actual mapping between MATLAB functions and library functions is also non-trivial. Even though MATLAB makes use of both the LAPACK and FFTW libraries internally, these libraries do not have equivalent functions for operations such as matrix divide “mrdivide” or the FFT-based FIR filtering “fftfilt,” which is part of the signal-processing toolbox.

Preview of a better way…
This part highlighted some of the pitfalls in developing MATLAB library functions in C and interfacing these functions with external functions or libraries.

Part 3 of this article will present how Catalytic MCS can automatically generate C code from MATLAB that is easy to integrate with other C functions and that interfaces common libraries automatically. In addition, the Catalytic Function Library makes it possible to automatically generate functionally-equivalent C code for many MATLAB functions.

About the authors
Marc Barberis leads the applications group at Catalytic Inc. Prior to Catalytic, he held several positions in wireless design and system level simulation tools . His interests include physical layer for 3G and digital receiver algorithms. Marc holds a MS in EE from Ecole Nationale Superieure des Telecommunications de Paris. He can be reached at marc@catalyticinc.com.

Luc Semeria is product manager at Catalytic Inc. Prior to Catalytic, he held several positions at Synopsys Inc. His research interests include compilers, EDA tools, computer architecture, and DSP algorithms. Luc holds a Ph.D. in Electrical Engineering from Stanford University. He can be reached at luc@catalyticinc.com.

Related articles:

Lien : http://systeme.developpez.com

Vous cherchez

Architecture des ordinateurs
Systèmes d’exploitation
Systèmes temps réels
Systèmes embarqués
Systèmes répartis
Réseaux : Généralités
Réseaux : Bus
Parallélisme
Grilles de calcul
Sécurité
Compression audio et vidéo

http://www.robochamps.com

While there has long been a large audience interested in robotics, there have also been a number of barriers to entry, both real and perceived. Robots are not widely available in traditional retail stores. If one could find a programmable robot, the cost was often times non-trivial. In addition, the ‘robot’ that could be purchased was often in the form of a kit and required hardware knowledge and skills. And if one could both find and afford a robot, there was a perception that programming one must be difficult.

RoboChamps is a new robotics programming league that removes those barriers to entry and makes robotics available to a broad audience. RoboChamps is based in simulation, which removes the barriers to entry of availability, cost, and deep hardware knowledge. RoboChamps is more specifically built on top of the simulation functionality provided in Microsoft Robotics Developer Studio 2008, which means that participants can program their robots using the .NET languages they are already familiar with.

In addition, a simulated robotics competition provides the opportunity for participants to engage in rich simulation environments and use robots that are unattainable via other means. For example, RoboChamps participants have the opportunity to navigate a rescue robot in a city struck by disaster, program a car to drive autonomously in a traffic filled city and drive a rover on the surface of Mars – all scenarios that would be financially prohibitive for most individuals.

RoboChamps is a league, and like most leagues has a season that is comprised of a series of competitions. In this league, these competitions are referred to as Challenges. These provide participants with a rich 3d, physics-enabled environment and a robot, and challenge participants to solve tasks in an environment-specific scenario.

The RoboChamps season culminates in an end of season tournament. The top four in the tournament will participate in a finals event where they will take their simulation code and apply it to real robots.

The Amazed Challenge is designed to measure your ability to program a simulated, autonomous robot that successfully navigates a 3-D virtual maze from beginning to end.

L’édition 2008 du magazine COMSOL News vient de paraître!

Demandez le dès maintenant:
- en version papier sur www.comsol.fr/COMSOL_News
- au format PDF en téléchargement sur http://cds.comsol.com/mg/b4816d331b55bb.zip

ou sur Gaubuali’s Webblog : comsol_news_2008

Au menu, 36 pages de cas utilisateurs et d’infos techniques:

* Comment la foudre agit-elle sur la carlingue d’un avion - SAAB
* Concevoir un procédé efficace de mise en forme des matériaux composites - RocTool
* Développer un système de revitalisation de l’air pour les voyages spatiaux vers Mars - NASA
* Améliorer les tests de durée de vie des circuits semi-conducteurs - STMicroelectronics
* Produire des capteurs pour l’automobile - Continental Corp.
Etc

Chaque article décrit en détail l’intérêt de la simulation et sa valeur ajoutée en matière de conception/production et d’avancée des projets.

N’hésitez pas à me contacter pour toute précision!

Cordialement,
Oumnia SQUALLI

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

COMSOL France - Grenoble & Paris
WTC, 5 Place R. Schuman
F-38000 Grenoble
oumnia.squalli@comsol.fr
tel : 04 76 46 49 01
fax : 04 76 46 07 42

lien : http://technofriends.in/2008/04/28/how-to-use-gmail-to-remote-control-your-pc/

Its a known fact that Gmail is the most popular email service available today. Though, utilities for using Gmail as a disk space were out pretty long back; there is another interesting utility called GCALDaemon which can be used to remote control your PC using Gmail.

GCALDaemon is an OS-independent Java program that offers two-way synchronization between Google Calendar and various iCalendar compatible calendar applications. GCALDaemon was primarily designed as a calendar synchronizer but it can also be used as a Gmail notifier, Address Book importer, Gmail terminal and RSS feed converter. GCALDaemon uses very less memory ( ~ 10-20 MB) and runs in service mode on Windows NT/2000/XP.

GCALDaemon, when initially installed, is not configured to do anything. Based on the services you wish to use, it should be configured. In this post, we shall be using GCALDaemon to remote control our PC. As a practical implementation, this scenario can be useful to users who have a very protected network but still wish to do certain tasks with it. It assumes that port 80 of your computer is open. )

GCALDaemon can be used to remote control your PC

GCALDaemon’s ‘mailterm’ service enables Gmail users to remotely control their PC by sending an email to their Gmail account. This management service keeps checking a Gmail inbox regularly, if it finds an email from a trusted sender and with a secret subject, it reads and executes a specified script file. Then GCALDaemon sends back a response, which contains the script’s output. Most mobile carriers and recent phones have built-in support for sending email through SMS gateways, therefore a simple cellural phone should be enough to manage a computer.

In order to configure ‘mailterm‘ service follow the steps mentioned below

1.) Install GCALDaemon. You can download GCALDaemon from here

2.) Enable IMAP on your Gmail. Check my previous postGmail gets IMAP Support for further information on this.

3.) You will need to encode your Password by starting out the Password Encoder application. This application takes in your Gmail Password and encodes it. Copy the encoded password.

GCALDaemon-Password Encoder feature encodes the password

4.) Open ‘gcal-daemon.cfg’ and edit the same with your favorite text editor. On Windows, this file is located in C:\Program Files\GCalDaemon\conf\gcal-daemon.cfg as part of the default installation. In case, if you have chosen to change the installation path, please look for the file in the respective location.

A) Set the ‘mailterm.enabled’ property to ‘true’
B) Set the ‘mailterm.google.username’ property to your Gmail address
C) Set the ‘mailterm.google.password’ property to your encoded password

Configuring Mailterm in GCALDaemon

5.) At the time of setup, you may choose your own unique email subject for mailterm. This subject must be at least 6-8 characters long and contain a combination of letters and numbers. Basically, you do not want any word or number which can be associated with you, or typical in ordinary messages. The subject is case sensitive. Start the password encoder again, input your mailterm subject and press ENTER. Copy the encoded subject.

Cinfiguring Mailterm on GCALDaemon- Part2

6.) 6) Edit the ‘gcal-daemon.cfg’ with text editor.

GCALDaemon- Configuring Mailterm Part3

A) Put the encoded subject for the variable ‘mailterm.mail.subject’.
B) Put the list of the trusted e-mail senders for the variable ‘mailterm.allowed.addresses’.

7.) Create a new script file (BAT or SH) and save this file into the mailterm’s scipt folder (e.g. ‘/scripts/ls.bat‘). The folder’s location is determined by the ‘mailterm.dir.path’ property in the gcal-daemon.cfg file.

Configuring Mailterm on GCALDaemon-4

8) Setup finished - launch GCALDaemon.

9) Create a new mail message, put your mailterm subject for the mail’s title, and enter you mailterm command in script name [optional parameters] format. You can use either a single quotation mark (’) or quotation marks (”) to enclose script parameters.

Configuring Mailterm on GCALDaemon - Part5

10) Click on ‘Send’ button. You will receive the script’s output within 10 minutes after submitting your mail.

Configuring mailterm on GCALDaemon - Part7

You can further do some fine adjustments to this installation. Please visit the official page of GCALDaemon for further details.

Also read: Interesting Gmail Hacks

How-to Exclude Chat from Gmail Search Results

How-to show unread mails at the top in your inbox in Gmail.

Ce tutoriel est créé par mon collègue Ali Diouri, responsable des calculs mathématiques dans mon équipe. Je vous fournit les documents en .pdf : tutorial_rlc_serie

Le paquet complet : http://www.megaupload.com/?d=39T6VGCW (je n’ai pas trouvé de hôtes)

Quelques mots : En commençant le GUI en Matlab, je n’ai pas trouvé beaucoup d’aide en graphique en ligne. C’est pourquoi on a décidé de faire un petit tutorial pour ceux qui commencent le GUI en Matlab.

On a décidé de prendre le circuit RLC en série pour développer cet outils. Cette exemple permet aussi à ceux qui voulaient comprendre circuit RLC en série.