You are currently browsing the category archive for the 'fiche méthode' category.
lien : http://www.embedded.com/columns/guest/207402542?_requestid=825240
en français par google.translate: lien
Si les champions de Linux embarqué disent que Linux embarqué est terrible, pourquoi tout le monde veut risquer leur produits ou leur entreprise? [...]
If embedded Linux champions are saying that embedded Linux is terrible, why would anyone want to risk their products or their company on it?
Embedded Linux is the most hyped embedded operating system ever. It is promoted as inexpensive, high quality, high productivity, reliable, widely available, and well supported. It is none of these things, as two of its greatest proponents have recently pointed out. Wind River Systems and MontaVista Software, companies that each describe themselves as “the leader” in embedded Linux, have both initiated marketing campaigns touting the horrors of using embedded Linux.
In the January/February 2008 issue of Military Embedded Systems, Jim Ready, the founder and chief technology officer of MontaVista, says “a [develop-it-yourself] embedded Linux distribution [is] a significant investment (read ‘big bucks’) in time and money.” He estimates the three-year cost of a large scale embedded Linux deployment at $19,623,750. Here are some other quotes from the article:
“To keep abreast of the changes occurring on a daily basis a developer needs to monitor the email traffic of 11 different and unsynchronized open source projects… up to 5,000 messages a day with 1,000 of these being patches that need to be evaluated and possibly applied to the source base. Simply ignoring the traffic, figuring that the system in use seems to be working well enough, can lead to disastrous consequences later.
“A recent security patch that took all of 13 lines of code to implement against an embedded Linux system would have taken more than 800k lines of source patches to implement, if the previous trail of patches had been ignored. It’s a classic case of pay now or really pay later.
“If there ever were a situation where the ’software money pit’ could really take hold, it’s in owning 30 million lines of constantly changing source code. Even in the simplest case, the development costs are typically in the millions of dollars.”
Wind River delivers the same message in a recent full-page advertisement. It asks: “Choosing Linux as your next device operating system?” It answers: “CHAOS” in large crooked letters, followed by “fatal error,” “system crash,” “game over,” and “panic.”
Even the greatest critics of embedded Linux have never been so harsh. The experts say that embedded Linux is “CHAOS” and “a money pit.” With friends like these, who needs enemies?
One would expect Wind River and MontaVista to tout the advantages of their embedded Linux support, but why trash the product on which their business is based? If they are being unfair to embedded Linux, the Linux community will rise up to denounce them, destroying their embedded Linux support business.
It’s more likely that Wind River and MontaVista are telling it as they see it–for marketing purposes. Marketing usually puts forward a problem (bad breath, headaches) that many potential customers will relate to, and then promises a solution. Why would Wind River and MontaVista put forward the problem of embedded Linux nightmares in marketing materials unless they think many potential customers have experienced those nightmares and need a solution? Wind River and MontaVista are certainly in a position to know how hard it is to use embedded Linux, because they are using it, supporting it, and selling it. And since their business is trying to pick up the pieces for companies that have already failed with embedded Linux, they have heard plenty of horror stories.
Wind River and MontaVista each say that they can tame the embedded Linux monster and make it work for customers. But can they? Trying to fix embedded Linux for eight years, MontaVista is reported to have lost over $60,000,000, going through five rounds of venture capital, three rounds of layoffs, and three CEOs in the last two years. Since jumping on the Linux bandwagon, Wind River has gone from profitability to losses, recently announcing a layoff of 7% of their staff.
So why are Wind River and MontaVista bashing embedded Linux? Each year, Embedded System Design magazine carries out a survey of embedded systems developers. Over a two year period from 2005 to 2007, the percentage of developers using embedded Linux and the percentage planning to use embedded Linux have both declined. And even more important, the percentage not interested in embedded Linux has nearly doubled.
According to ESD’s analysis, most of those who are reasonable targets for embedded Linux (those with PC-like applications) have already adopted it. The rest have learned it is not appropriate and are moving on. See the article “Annual study uncovers the embedded market” (Richard Nass, www.embedded.com/design/opensource/201803499?pgno=2) for details of survey.
It seems clear what is happening: Wind River and MontaVista are trying to get the dwindling number of disenchanted embedded Linux users to pay them “big bucks” to escape the embedded Linux nightmare. They hope that if they can get enough customers signed up, they will finally get enough money to tame the beast.
But what happens if they cannot? There are indications that they may have exhausted the market. If Wind River fails to stem the tide, they will need to drop their support for embedded Linux to return to profitability. And if MontaVista doesn’t show some sign of stemming their losses soon, their investors will pull the plug. When Wind River and MontaVista abandon embedded Linux, their customers will have to live the embedded Linux nightmare that Wind River and MontaVista are telling them–all too clearly–that they will have.
This embedded Linux bashing from embedded Linux’s strongest proponents should give pause to those who are thinking through their embedded operating system strategy. If embedded Linux champions are saying that embedded Linux is terrible, why would anyone want to risk their products or their company on it?
Why would anyone use a product that its proponents say is awful? Would you buy a car from a salesman who admitted the car was a piece of junk just because he said he had a great service department? That’s what embedded Linux’s friends suggest that you do. With friends like these, who needs enemies?
Dan O’Dowd is the founder and chief executive officer of Green Hills Software. Prior to Green Hills Software, O’Dowd managed compiler and operating systems development at National Semiconductor, where he designed the architecture for the NS32000 32-bit microprocessor. O’Dowd holds a bachelor of science in engineering from the California Institute of Technology.
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.

Part2:
Complex functions and C interfaces
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.
part 3: Code generation and verification
In the first two parts of this series, we navigated the waters of MATLAB to C translation and encountered some of the Charybdis and Scylla monsters that await the unsuspecting engineer along the way. By now, it should be plain indeed, that translating MATLAB to C, short of being a Homeric Odyssey, is anything but an easy task.
In this third and last part, we will explore verification and emphasize how automatic C code generation solves most of the issues described so far. We will illustrate this approach with Catalytic MCS (MATLAB to C Synthesis).
Making sure the C is correct
Verifying that the generated C code matches the original MATLAB code is both extremely important and challenging.
Thankfully, various techniques exist for such verification. A popular albeit tedious method consists of using files to pass input and output data, and comparing the results between the MATLAB code and C code. A more systematic method consists of turning the generated C code into a compiled MEX-file that can be called directly from MATLAB like any other function.
The mex command can be used from the MATLAB command line to compile C code into a MEX-file. The mex command uses the MEX API, which provides functions to pass data between your C code and MATLAB. The MEX-file guide provides more information on how to write your own MEX-files.
Turning your C model into a MEX-file allows you to rerun your original MATLAB simulation with no change and ensure the results are identical. However, you need to write a MEX wrapper function, which passes all the data you need to exchange between MATLAB and C. The wrapper uses arcane functions provided by the MEX-API. This task is also error prone—crashes, segmentation violations or incorrect results can easily occur if the MEX wrapper does not allocate and access the data properly.
The case for automation
Automating the generation of C code from the MATLAB file can help overcome these problems. Conceptually, an automated MATLAB-to-C converter offers the following advantages:
- The generated code is correct by construction
- The MATLAB and C code are always in-sync
- You can spend more time in MATLAB developing and tuning your algorithms rather than writing and debugging low-level C-code
- Updates to the algorithms result in automatic, immediate update of the C code
However, automatic translation of MATLAB code to C code raises a few important questions:
- How powerful is the set of MATLAB commands that can be translated to C? The solution loses much of its appeal if it requires the algorithm designer to restrict his style drastically. The designer must then heavily rewrite his MATLAB code, a time-consuming and error prone process. Furthermore, the code loses a lot of its flexibility.
- How efficient is the generated code? Are advanced techniques for memory management and C-code optimization available?
- Does the generated C-code easily interface with the existing code for your application?
- How readable is the resulting C code? Is the C-code understandable and maintainable? Does the generator retain the structure of the original MATLAB file?
- Can the code generator target specific libraries for a given application?
We will review all these pitfalls when looking at Catalytic MCS. But note that code generation from MATLAB isn’t a new concept, although it has received limited attention.
The AccelDSP tool from Xilinx targets the FPGA market with Verilog/VHDL code generation from MATLAB. (For a related how-to article, see Generate FPGA designs from M-code.) This tool relies heavily on library modules to obtain the highest quality results out of a quantized design.
More recently, The Mathworks introduced a restricted subset of the MATLAB language called “Embedded MATLAB,” for which Real-Time Workshop can generate C code. The subset is aimed at addressing the needs of embedded designers, who do not perform algorithm exploration or mind restricting their MATLAB style for an embedded target. In particular, Embedded MATLAB avoids a lot of the issues described in the previous two parts of this series by requiring rewrite of the MATLAB in Embedded MATLAB.
In the remainder of this article, we’ll demonstrate how you can use Catalytic MCS to generate high quality, flexible C code from existing MATLAB code, which was written by algorithm experts without consideration for matrix size or type declaration.
Let’s get back to our initial, simple example from part 1:

This is a typical example of the power of MATLAB: you need not think about memory allocation, matrix size, naming or declaration of variables—MATLAB takes care of these.

(Click to enlarge)
Figure 1. Catalytic MCS GUI and automatic C-code generation.Catalytic MCS accepts this code as-is and translates it to the C code shown in Figure 1. (A confession: the C code shown in part I was generated by Catalytic MCS).
We still need to show how MCS helps solve the core issues mentioned earlier. Let’s revisit that now.
Polymorphism
In MATLAB, polymorphism implies that a function can behave differently depending upon the type of the input parameters.
Consider, for example, the following trivial function:

The C code for this function would be completely different if both var1 and var2 are matrices or var1 is a matrix and var2 a scalar.
Catalytic MCS automatically analyzes the M-code and extracts the type (real, complex, etc.) and shape (scalar, row, column, matrix, etc.) of variables. Based on this analysis, MCS generates C code that works for all possible configurations. This ensures that the C code behaves identically to the MATLAB code.
The default generated code, shown in Figure 2 on the left, includes many options to account for the different possible sizes of var1 and var2. MCS analyzes the “polymorph” function and computes an element-element multiply (if var1 or var2 is scalar) or matrix multiply. MCS analysis can also identify that the multiply is for real floating-point data, not complex data.
If you select the input variables var1 and var2 to be 2×5 and 5×4 in size, respectively, MCS generates the very much simplified code shown on the right.

(Click to enlarge)
Figure 2. The MCS GUI and two possible C code generated from the MATLAB file: on the left, the most general C code, which works for all types of var1 and var2 matrices; on the right, a specialized version for fixed-size matrices.MCS also optimizes the generated code. For example, if a parameter to a function is a constant, MCS uses advanced compiler optimization techniques such as constant propagation and automatic function specialization. Note that you need not constrain all sizes and types to generate tighter code—doing so for your input variablesis usually sufficient. The MCS analysis tool will propagate such information automatically. Also, if your code requires use of dynamic sizes, a range of sizes (instead of fixed sizes) can be specified.
MATLAB excels at representing matrices and matrix operations. However, implementing matrix operations and concatenations in C is challenging.MCS automatically generates the necessary loops and indexing for vector, matrix or N-dimensional array operations. As shown in the previous examples, MCS also uses 0-based indexing as required for C code.
MCS allocates the memory needed to perform concatenations and self-concatenations such as:

MCS also optimizes the generated C code. The following example illustrates one such optimization:
Consider the two simple vector statements:

In this case, creating a temporary matrix x and then computing the exponential of x would be inefficient. It would result in extra memory use, two distinct loops, and potential performance degradation due to cache misses. Instead, MCS performs an advanced “loop fusion” optimization, using only one loop and converting the temporary matrix “x” into a simple scalar temporary “itemp_0.” This is illustrated in Figure 3.

(Click to enlarge)
Figure 3. Example of loop fusion performed by Catalytic MCS.This case is very trivial. However, it illustrates that the optimizations MCS performs can require careful thought from a C implementer.
Verifying your C code and catching unintentional array extensions
As stated earlier, the best way to check the behavior of your C code is to run it in the MATLAB context using the MEX interface. Writing the interface code by hand is tedious and error-prone. However, MCS automates this generation. MCS further guarantees that the code is correct by construction, but you can verify this yourself.
In addition, the generated code can also automatically catch unexpected errors at run-time. Let’s look at a case where the MATLAB happens to mistakenly write beyond an array boundary:

This function extends x if N is greater than 15.
MCS accepts the code but provides (on request) debugging information, which points to the exact problem when you execute the generated C code. In the screenshot below (Figure 4), MCS is used to generate the C-code and automatically compile it into a MEX-file for verification, directly from the MATLAB command line.

Figure 4. Debugging support in MCS.Much like other compilers, which provide both “debug” and “optimized” modes, MCS provides both a “safe” mode and “fast” modes for debugging or optimization.
By default, MCS generates “safe” code, which points out any potential problem (array extension, out-of-bound array access, incompatible sizes in operations, etc.) at run-time. This is invaluable for debugging your design. Once the model has been verified and behaves correctly, MCS can be invoked using the “-fast” command-line option to generate “fast” code. “Fast” code bypasses error checking and is tight and fast.
Interfacing the generated code
One critical aspect of MCS generated C code is the ease of integrating it with external C code and libraries.
For instance, most existing C code uses row-major layout, meaning that consecutive memory locations are on the same row (as opposed to column). Straightforward code generation from MATLAB yields column-major code. You can introduce an additional transposition at the interface to get around this (as explained here), but this is both inefficient and costly. MCS can generate either row-major or column-major code. This allows data to be passed smoothly and directly between the generated code and the code it needs to be integrated with (such as libraries, C application, and other MATLAB blocks).
For example, we are used to thinking about VGA resolution as 640×480. However, C code typically stores such an image as 480×640 (that is, 480 lines and 640 columns), and not 640×480. This highlights the importance of carefully considering the choice of your interface.
Figure 5 shows two pieces of code generated by MCS for the same MATLAB source file: the piece on the left uses column-major format, the right one uses row-major. If this code needs to be interfaced with external C code, you would require the row-major version.

(Click to enlarge)
Figure 5. Example of column-major code (left) and row-major code (right) generated from the same MATLAB source file.Another often neglected topic is the interfacing of code with complex numbers. MCS also provides options to automatically split a complex variable into two separate variables holding the real and imaginary parts, or to interleave real and imaginary parts in arbitrary order.
Having control over the memory layout and interfaces of multi-dimensional arrays and complex data dramatically simplifies the integration of the C code generated from MATLAB within an application or with existing libraries. MCS, by providing easy interfacing capability, eases interfacing of code with libraries such as FFTW (for discrete Fourier and Cosine transforms), LAPACK (for all linear algebra operations), or target-specific ones.
Conclusion
Automatic C code generation with MCS from normal, unconstrained MATLAB code can help bypass many pitfalls during the translation process.
Possible applications include:
- Running C simulations on a general purpose processor
- Targeting embedded applications
- Accelerating simulations
- Getting a parameterizable, golden C model as a reference for implementation
In general, when considering an automatic translation tool for MATLAB to C, the following may be helpful:
- Consider whether or not a lot of pre-existing MATLAB code exists. If legacy code is unavailable and you are writing new code, restricted MATLAB support will hurt you less than having to rewrite a lot of existing MATLAB code to fit the tool’s restrictions.
- Ensure that MATLAB coding style restrictions do not limit describing your algorithm efficiently and conveniently
Assess the quality of the generated C code. Beyond that, assess how well the tool answers your needs in terms of interfacing (for example, generating row-major code for easy integration with external C code).
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
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’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.
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
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.
6.) 6) Edit the ‘gcal-daemon.cfg’ with text editor.

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.
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.
10) Click on ‘Send’ button. You will receive the script’s output within 10 minutes after submitting your mail.
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
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.
Lien : http://www.lpmi.uhp-nancy.fr/realisation/USB/usbhub.html
Réalisez un Hub USB schéma complet avec le circuit imprimé. Hub 4 ports alimentation par le bus.
Réalisation Pautex JF ( LPMI 1999 )
Première sur le Net le schéma d’un Hub USB pour votre ordinateur, ce montage est en cours de test cette page sera mise à jour lors des tests complet et de l’assurance de fonctionnement de ce Hub. Le cout est très faible puisque vous devez vous procurer seulement les connecteurs USB et le quartz 6 MHz (RadioSpares) par exemple. Voir le site Texas pour la disponibilité des autres composants.
Keywords : USB, Hub USB
Schéma du montage :

Description :
La réalisation de ce Hub nécessite l’obtention de quelques CI que vous trouverez sur le Net.
Liste des composants de ce montage HUB :
| SN75240P TPS2041D TPS76433DBVR TUSB2046VF MAX821 Quartz 6 MHz Connecteur A Connecteur B |
3 1 1 1 1 1 2 1 |
Protection de bus (Texas ) Commutateur d’alimentation ( Texas ) Alimentation régulé 3,3 V ( Texas ) controleur USB ( Texas Instrument ) Power on reset ( MAXIM ) Quartz USB type A double USB type B simple |
Ces composants sont tous disponibles sur les sites Internet des constructeurs en échantllons gratuits.
Circuit Photo du montage :

Fichiers au format pdf du circuit imprimé de ce montage
Réalisez l’impression de ces fichier sur transparents ou calque à l’aide d’une imprimante laser le circuit imprimé deux faces ne présente pas de difficultées particulière, la soudure du composant TSU2046 est délicate, un petit fer à souder convient parfaitement. On trouvera la disposition des élément sur le schéma ci-dessous.
Disposition des éléments de ce montage :

Lien : http://doc.ubuntu-fr.org/tutoriel/script_shell
Présentation
Un script shell permet d’automatiser une série d’opérations. Il se présente sous la forme d’un fichier contenant une ou plusieurs commandes qui seront exécutées de manière séquentielle.
Règles de base lors de l’écriture d’un script
-
Des vérifications approfondies doivent être effectuées sur TOUTES les commandes utilisées.
-
Des commentaires détaillés doivent apparaître lors de chaque étape. De même, chaque étape doit être suivie d’un “echo <voici ce que je fais>” (particulièrement utile notamment lors du débuggage).
-
Lors d’une mise à jour, un fil de discussion doit être précisé pour tracer les bugs éventuels.
-
Avertir les utilisateurs des dégâts que peuvent causer les commandes utilisées. (Ces deux dernières remarques ne concernent bien sûr que les scripts que l’on souhaite diffuser.)
Évidemment ces conseils sont utiles au débutant…
Exemple: Supposons que vous avez une base de données, avec 3 catégories d’enregistrements possibles: éléphant bleu, éléphant blanc, éléphant rose ayant chacun 30 individus. Votre script doit compter le nombre d’éléphants bleus et blancs. Deux possibilités s’offrent à vous:
-
calculer le nombre d’éléphants bleus + éléphants blancs
ou
-
calculer le nombre total d’éléphants - nombre d’éléphants roses
Quel algorithme choisissez-vous? Résultat: Le premier car dans le deuxième il faut d’abord calculer le nombre total d’éléphants, donc un calcul en plus.
OUUUUUUIIIIIIIIIIIIIIIIIIIIIII !
Ecrire un script
Si vous voulez écrire un programme sh, vous avez deux possibilités :
-
soit vous tapez dans un shell toutes les commandes
-
ou alors vous rassemblez toutes les instructions copiées par ci par là dans un fichier sh.
A titre d’exemple, saisissez ces quelques lignes dans votre éditeur préféré :
#!/bin/bash
# indique au système que l’argument qui suit est le programme utilisé pour exécuter ce fichier.
# En cas général les “#” servent à faire des commentaires comme ici
echo Mon premier script
echo Liste des fichiers :
ls -la
exit 0
Le résultat de ce script est d’écrire à l’écran “Mon premier script”, puis en dessous “Liste des fichiers :”, et enfin la liste des fichiers avec la commande `ls -la`.
Comme vous l’avez compris, la commande `echo` sert à écrire quelque chose à l’écran.
Exécuter un script
D’ici, j’entends déjà les débutants dire :
Et bien il suffit de se placer dans le dossier où est le script, et de lancer
bash nom_du_script
Si vous voulez l’exécuter avec “.”, il faut le rendre exécutable avec `chmod`. Pour ceci tapez dans le shell la commande qui suit :
chmod +x nom_du_script
Puis vous pouvez exécuter le script en faisant :
./nom_du_script
Les différents types de shells
Comme vous avez surement dû l’entendre, il existe différents types de shells, dont le plus connu est, comme vous l’aurez deviné, ’shell,’ qui signifie coquille. Il existe aussi:
-
bash (Bourne Again SHell) : conçu par le projet GNU, shell linux ;
-
rbash : un shell restreint basé sur bash. Il existe de nombreuses variantes de bash ;
-
csh, tcsh : shells C, créés par Bill Joy de Berkeley ;
-
zsh, shell C écrit par Paul Falstad ;
-
ksh,pdksh : shells korn, écrits par David Korn ;
-
rc : shell C, lui aussi conçu par le projet GNU ;
-
tclsh : shell utilisant Tcl ;
-
wish : shell utilisant Tk ;
Il existe bien entendu beaucoup d’autres types de shells.
Shell (sh) est en fait un lien vers /bin/bash, tout comme rbash.
Les structures de contrôle
Les tests : `if`
Avant de commencer à faire des scripts de 1000 lignes, il serait intéressant de voir comment se servir des variables, et des instructions if, then, elif, else, fi. Cela permet par exemple de faire réagir le script de manière différente, selon la réponse de l’utilisateur à une question.
En bash, les variables ne se déclarent généralement pas avant leur utilisation, on les utilise directement et elles sont créées lors de sa première mise en œuvre.
Pour pouvoir voir la valeur d’une variable il faut faire précéder son nom du caractère “$”.
Exemple
#!/bin/sh
echo -n "Voulez-vous voir la liste des fichiers Y/N : "
read ouinon
if [ "$ouinon" = "y" ] || [ "$ouinon" = "Y" ]; then
{
echo “Liste des fichiers :”
ls -la
}
elif [ "$ouinon" = "n" ] || [ "$ouinon" = "N" ]; then
{
echo “Ok, bye! ”
}
else
{
echo “Il faut taper Y ou N!! Pas $ouinon”
}
fi
Explication
Ce script peut paraître simple à première vue mais certaines choses prêtent à confusion et ont besoin d’être expliquées en détail.
Tout abord, le `echo -n` permet de laisser le curseur sur la même ligne, ce qui permet à l’utilisateur de taper la réponse après la question (question d’esthétique).
L’instruction `read` permet d’affecter une valeur ou un caractère à une variable quelconque, en la demandant à l’utilisateur. (NOTE: En bash, la variable est considérée comme une chaîne même si celle-ci contient une valeur numérique, et les majuscules sont considérées différente des minuscules, $M != $m).
Ensuite vient l’instruction conditionnelle `if`. Elle est suivie d’un “[" pour délimiter la condition. Attention, la variable est mise entre guillemets car dans le cas où la variable est vide, le shell ne retourne pas d'erreur, mais en cas contraire, l'erreur produite ressemble à:
[: =: unaryoperator expected
L'opérateur `||` signifie "ou" (il existe aussi `&&` pour "et"). On peut définir une table de vérité pour ces deux opérateurs, où 1 représente une assertion vraie et 0 une assertion fausse :
Table de vérité de ||
| Comparaison | Résultat | calcul |
|---|---|---|
| 0 ou 0 | 0 | 0+0=0 |
| 0 ou 1 | 1 | 0+1=1 |
| 1 ou 0 | 1 | 1+0=1 |
| 1 ou 1 | 1 | 1+1=1 |
Dès que l'une des deux assertions est vérifiée, la condition globale l'est aussi.
Table de vérité de &&
| Comparaison | Résultat | calcul |
|---|---|---|
| 0 et 0 | 0 | 0*0=0 |
| 0 et 1 | 0 | 0*1=0 |
| 1 et 0 | 0 | 1*0=0 |
| 1 et 1 | 1 | 1*1=1 |
Les deux assertions doivent être vérifiées pour que la condition le soit aussi.
Enfin, on ferme le crochet, suivi d'un point virgule ou d'un saut de ligne pour exécuter la commande `then` qui applique ce qui vient après, si la condition est respectée.
Les "{" servent à bien délimiter le bloc d'instructions suivant le `then`, cela permet juste de facilement lire le code, de mieux se repérer.
Ensuite, `elif` sert à exécuter une autre série d'instructions, si la condition décrite par `if` n'est pas respectée, et si celle fournie après ce `elif` l'est.
Enfin, `else` sert à exécuter un bloc si les deux conditions précédentes ne sont pas respectées. (ah les jeunes, ils respectent plus rien de nos jours
).
`fi` indique la fin de notre bloc d'instructions if, ce qui permet de voir où se termine toute notre portion de code soumise à une condition.
J'ai quelques petites commandes pratiques à vous donner :
sh -n nom_du_fichier
Cette commande vérifie la syntaxe de toutes les commandes du script, pratique quand on débute et pour les codes volumineux.
sh -u nom_du_fichier
Celle-ci sert à montrer les variables qui n'ont pas été utilisées pendant l'exécution du programme.
Voici le tableau des opérateurs de comparaison, ceux-ci peuvent s'avérer utiles pour diverses raisons, nous verrons un peu plus loin un exemple:
Opérateurs de comparaison
| Syntaxe | Fonction réalisée |
|---|---|
| -e fichier | Vrai si fichier existe. |
| -d fichier | Vrai si fichier existe et est un répertoire. |
| -f fichier | Vrai si fichier existe et est un fichier 'normal'. |
| -w fichier | Vrai si fichier existe et est en écriture. |
| -x fichier | Vrai si fichier existe et est exécutable. |
| f1 -nt f2 | Vrai si f1 est plus récent que f2. |
| f1 -ot f2 | Vrai si f1 est plus vieux que f2. |
Exemple, vérifier qu'un fichier existe:
#!/bin/sh
echo -n "Entrez un nom de fichier: "
read file
if [ -e "$file" ]; then
{
echo "Le fichier existe!"
}
else
{
echo "Le fichier n'existe pas, du moins n'est pas dans le répertoire d'exécution du script"
}
fi
exit 0
La seule chose qui prête à confusion est que l’on vérifie seulement si le fichier ‘file’ est dans le répertoire où le script à été exécuté.
La commande `while`
La commande while exécute ce qu’il y a dans son bloc tant que la condition est respectée:
#!/bin/sh
cmpt=1
cm=3
echo -n "Mot de passe : "
read mdp
while [ "$mdp" != "ubuntu" ] && [ "$cmpt" != 4 ]; do
echo -n “Mauvais mot de passe, plus que “$cm” chance(s): ”
read mdp
cmpt=$(($cmpt+1))
cm=$(($cm-1))
done
echo “Non mais, le brute-force est interdit en France !!”
exit 0
On retrouve des choses déjà abordées avec `if`. Le `&&` sert à symboliser un “et”, cela implique que deux conditions sont à respecter. Le `do` sert à exécuter ce qui suit si la condition est respectée. Si elle ne l’est pas, cela saute tout le bloc (jusqu’a `done`). Je vous vois d’ici dire :
Cette partie du code sert tout simplement à réaliser une opération arithmétique. A chaque passage, ‘cmpt = cmpt+1′ et ‘cm = cm-1′.
`while` permet de faire exécuter la portion de code un nombre déterminé de fois. La commande `until` fait la même chose que la commande `while` mais en inversant. C’est a dire qu’elle exécute le bloc jusqu’a ce que la condition soit vraie, donc elle s’emploie exactement comme la commande `while`.
La commande `case`
Regardons la syntaxe de cette commande, qui n’est pas une des plus simples :
case variable in
modèle [ | modèle] …) instructions;;
modèle [ | modèle] …) instructions;;
…
esac
Cela peut paraître complexe mais on s’y habitue quand on l’utilise.
Mais a quoi sert cette commande ?
Elle sert à comparer le contenu d’une variable à des modèles différents. Les ;; sont indipensables car il est possible de placer plusieurs instructions entre un modèle et le suivant. Les ;; servent donc à identifier clairement la fin d’une instruction et le début du modèle suivant.
Exemple:
#!/bin/sh echo -n "Etes-vous fatigué ? " read on case "$on" in oui | o | O | Oui | OUI ) echo "Allez faire du café !";; non | n | N | Non | NON ) echo "Programmez !";; * ) echo "Ah bon ?";; esac exit 0
Je crois que la seule chose qui mérite vraiment d’être expliquée est `* )`. Cela indique tout simplement l’action à exécuter si la réponse donnée n’est aucune de celle données précédemment.
Il existe aussi plusieurs structures pour les modèles, telles que:
case "$truc....." in [nN] *) echo “Blablabla…”;; n* | N* ) echo “Bla….”;;
Et plein d’autres encore…
On mélange tout ça
Pour vous donner une idée précise de ce que peuvent réaliser toutes ces instructions, j’ai fait un petit script censé refaire un prompt avec quelques commandes basiques :
#!/bin/bash
clear
echo
echo #################### Script ############################
echo
echo #############################
echo -n LOGIN:
read login
echo -n Hôte:
read hote
echo #############################
echo
echo ### Pour l’aide tapez help ###
echo
while [ 1 ]; do # permet une boucle infinie
echo -n “”$login”@”$hote”$ ” # qui s’arrête avec break
read reps
case $reps in
help | hlp )
echo A propos de TS –> about
echo ls –> liste les fichiers
echo rm –> détruit un fichier (guidé)
echo rmd –> efface un dossier (guidé)
echo noyau –> version du noyau linux
echo connect –> savoir qui est c’est dernièrement connecté;;
ls )
ls -la;;
rm )
echo -n Quel fichier voulez-vous effacer :
read eff
rm -f $eff;;
rmd | rmdir )
echo -n Quel répertoire voulez-vous effacer :
read eff
rm -r $eff;;
noyau | “uname -r” )
uname -r;;
connect )
last;;
about | –v | vers )
echo Script simple pour l’initiation aux scripts shell;;
quit | “exit” )
echo Au revoir!!
break;;
* )
echo Commande inconnue;;
esac
done
exit 0
Remarque
Comme vous l’avez remarqué, l’indentation a une place importante dans ce programme. En effet, celui-ci est plus lisible et cela évite aussi de faire des erreurs. C’est pourquoi je vous recommande de bien structurer le code que vous écrivez.
La commande for
L’instruction `for` exécute ce qui est dans son bloc un nombre de fois prédéfini. Sa syntaxe est la suivante :
for variable in valeurs; do instructions done
Comme vous l’aurez sans doute remarqué, on assigne une valeur différente à variable à chaque itération. On peut aussi très facilement utiliser des fichiers comme “valeur”. Rien ne vaut un exemple :
#!/bin/sh for var in $(ls *.txt); do echo $var done exit 0
On peut voir une syntaxe un peu particulière : `$(ls *.txt)`. Ceci sert à indiquer que ce qui est entre les parenthèses est une commande à exécuter.
On peut aussi utiliser cette instruction simplement avec des nombres, cela permet de connaître le nombre d’itérations :
#!/bin/sh for var in 1 2 3 4 5 6 7 8 9; do echo $var done exit 0
On peut très bien aussi utiliser d’autres types de variables, comme par exemple des chaînes de caractères :
#!/bin/sh for var in Ubuntu Breezy 5.10; do echo $var done exit 0
Il faut quand même faire attention au fait que Ubuntu Breezy 5.10 est différent de “Ubuntu Breezy 5.10″ dans ce cas. En effet, tous les mots placés entre “” sont considérés comme faisant partie de la même chaîne de caractères. Sans les “”, sh considèrera qu’il y a une liste de trois chaînes de caractères.
Les fonctions
Les fonctions sont indispensables pour bien structurer un programme mais aussi pouvoir le simplifier, créer une tâche, la rappeler… Voici la syntaxe générale de ‘déclaration’ d’une fonction:
nom_fonction(){
instructions
}
Cette partie ne fait rien en elle même, elle dit juste que quand on on appellera nom_fonction, elle fera instruction. Pour appeler une fonction (qui ne possède pas d’argument, voir plus loin) rien de plus simple:
nom_fonction
Rien ne vaut un petit exemple:
#!/bin/sh
#Definition de ma fonction
mafonction(){
echo 'La liste des fichiers de ce répertoire'
ls -l
}
#fin de la définition de ma fonction
echo 'Vous allez voir la liste des fichiers de ce répertoire:' mafonction #appel de ma fonction exit 0
Comme vous l’avez sans doute remarqué, quand on appelle la fonction, on exécute simplement ce qu’on lui a défini au début, dans notre exemple, echo… et ls -l, on peut donc faire exécuter n’importe quoi à une fonction.
Lien
Pour ceux qui souhaitent aller plus loin dans la conception de script shell, je vous recommande ce cours de chez developpez.com : http://marcg.developpez.com/ksh/
Bash parameters and parameter expansions. En anglais mais contient de nombreux exemples concernant la gestion et l’analyse des paramètres : http://www.ibm.com/developerworks/library/l-bash-parameters.html
Site original : http://freeengineer.org/learnUNIXin10minutes.html
Version en français : http://doc.ubuntu-fr.org/tutoriel/learn_unix_in_10_minutes
Avant Propos
Ce document a été rédigé il y a quelques années pour des étudiants en Dessin Assisté par Ordinateur (DAO) . Le but était d’avoir sur une page les commandes de base pour utiliser le Shell Unix (comme ça ils ne me demanderaient pas quoi faire lorsque quelqu’un leur donnerait une sauvegarde)
Ce document est copyrighté mais peut être reproduit selon les termes de la GFDL. Envoyez-moi vos commentaires, corrections ou tout autre ajout qui vous semble absolument nécessaire dans ce document.1)
Sections
Chemins
Les chemins de fichiers et de dossiers sous Unix utilisent le slash “/” pour séparer les noms des dossiers.
Exemples :
| / | Dossier “racine” |
| /usr | Dossier usr (sous-dossier du dossier “racine”) |
| /usr/STRIM100 | STRIM100 est un sous-dossier de /usr |
Se déplacer dans le système de fichier
| pwd | montre le nom du dossier de travail courant (Present Working Directory) |
| cd | change le dossier de travail pour un autre dossier |
| cd /usr/STRIM100 | change le dossier de travail pour /usr/STRIM100 |
| cd INIT | change le dossier de travail pour INIT, qui est un sous-dossier du dossier courant |
| cd .. | change le dossier de travail pour le dossier parent |
| cd $STRMWORK | change le dossier de travail pour le dossier défini par la variable d’environnement ‘STRMWORK’ |
Lister le contenu d’un dossier
ls liste le dossier de travail courant
ls -l dossier liste au format détaillé le dossier dossier
Par exemple :
$ ls -l /home/sheherazade/work/ drwxr-xr-x 4 sheherazade staff 1024 2004-04-04 09:40 ToDo -rw-r--r-- 1 sheherazade staff 767392 2004-04-04 14:28 scanlib.tar.gz ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ | | | | | | | | | | | | | | | | Propriétaire Groupe Taille Date Heure Nom | | | | Nombre de fichiers ou dossiers que le dossier listé contient | | | Permissions pour tous | | Permissions pour les membres du groupe staff |Permissions pour le propriétaire r = lecture (read), w = écriture (write), x = exécute (execute), - = pas de droits Type de fichier * : - = Fichier régulier, d = Dossier, l = Lien symbolique ou autre...
Modifier les permissions et les droits
chmod
En employant la méthode alphabétique:
Ce qu’il faut savoir:
-
u: utilisateur (user), g: groupe (group) et o: autres (other)
-
r: lire (read), w: écrire (write) et x: exécuter (execute)
chmod [ugo][+-=][rwx] fichier
Vous devez donc choisir le groupe à modifier (u, g, o) suivis du symbole + pour donner une permission, du symbole - pour la retirer ou du symbole = pour définir la permission exacte suivi des permissions à appliquer (r, w, x).
Par exemple pour accorder à l’utilisateur d’exécuter le fichier.
chmod u+x fichier
Ou pour retirer les droits d’écriture et d’exécution au groupe et aux autres.
chmod go-wx fichier
En employant la méthode numérique:
Il faut savoir que x=1, w=2 et r=4 ensuite vous additionnez les chiffres si vous voulez cumuler les droits. L’ordre des chiffres est propriétaire/groupe/autres.
Par exemple pour accorder la lecture, l’écriture et l’exécution pour le propriétaire et la lecture et l’exécution pour le groupe et les autres.
chmod 755 fichier
On a propriétaire/groupe/autres donc rwx/rx/rx donc 4+2+1/4+1/4+1 et donc 7/5/5.
Astuce pour ceux qui connaissent le binaire. On veut rwx lire/écrire/exécuter donc 111 en binaire qui vaut 7 en décimal. On veut r-x lire/pas ecrire/exécuter donc 101 en binaire qui vaut 5 en décimal.
chgrp
chgrp staff fichier
change le fichier fichier afin qu’il appartienne au groupe staff.
chown
chown sheherazade fichier
fait de sheherazade la propriétaire du fichier fichier.
chown -R sheherazade dir
fait de sheherazade la propriétaire du dossier dir et de tous ses sous dossiers.
Déplacer, renommer et copier des fichiers
| cp fichier_source fichier_destination | copie un fichier |
| cp -r dossier_source dossier_destination | copie un dossier |
| mv fichier1 nouveau_nom_fichier1 | déplace ou renomme un fichier |
| rm fichier1 [fichier2 ...] | supprime un fichier (ou une liste de fichiers) 2) |
| rm -r dossier1 [dossier2...] | supprime un dossier et tous ses sous-dossiers, à manier avec précaution |
| mkdir dossier1 [dossier2...] | crée un dossier |
| rmdir dossier1 [dossier2...] | supprime un dossier vide |
Visualiser et éditer les fichiers
| cat fichier | affiche le contenu du fichier à l’écran en ASCII |
| more fichier | affiche progressivement un fichier à l’écran : Entrer = descend d’une ligne, Espace = descend d’une page, q = quitte |
| less fichier | comme more, mais on peut utiliser la touche Page Précédente. Pas disponible sur tous les systèmes. |
| vi fichier | éditer un fichier avec l’éditeur vi. Tous les systèmes Unix ont un éditeur à la vi. |
| emacs fichier | éditer un fichier avec l’éditeur emacs. Pas disponible sur tous les systèmes. |
| head fichier | affiche les premières lignes d’un fichier |
| head -n fichier | affiche les n premières lignes d’un fichier |
| tail fichier | affiche les dernières lignes d’un fichier |
| tail -n fichier | affiche les n dernières lignes d’un fichier |
Shells
Le comportement de l’interface en ligne de commande diffère légèrement en fonction du programme shell utilisé.
Suivant le shell utilisé, quelques comportements peuvent être pratiques.
Vous pouvez connaître le shell que vous utilisez avec la commande :
printenv SHELL
Vous pouvez bien évidemment créer un fichier contenant une liste de commandes shell et l’exécuter comme un programme pour exécuter une tâche. On appelle cela un script shell. C’est en fait le but premier de la plupart des shells, et non pas le comportement interactif de la ligne de commande.
Variables d’environnement
Vous pouvez apprendre au shell à ‘mémoriser’ des informations pour utilisation ultérieure grâce aux variables d’environnement. Par exemple avec bash :
export CASROOT=/usr/local/CAS3.0
définit la variable CASROOT avec la valeur /usr/local/CAS3.0.
cd $CASROOT
change le répertoire de travail courant pour CASROOT.
export LD_LIBRARY_PATH=$CASROOT/Linux/lib
définit la variable LD_LIBRARY_PATH qui prendra la valeur CASROOT avec /Linux/lib ajouté à la fin, c’est-à-dire /usr/local/CAS3.0/Linux/lib.
printenv
affiche toutes les variables d’environnement
printenv CASROOT
affiche la valeur de la variable d’environnement nommée CASROOT : /usr/local/CAS3.0.
echo $CASROOT
fait exactement la même chose.
Historique Interactif
Une fonctionnalité de bash et tcsh (et parfois d’autres) est de pouvoir utiliser la touche “flèche vers le haut” pour accéder aux dernières commandes entrées, les éditer, et les re-exécuter.
Complétion des noms de fichiers
Une des fonctionnalités de bash et tcsh (et probablement d’autres) est de pouvoir utiliser la touche TAB pour compléter un nom de fichier tapé partiellement. Par exemple, si vous avez un fichier nommé constantine-monks-and-willy-wonka.txt dans votre répertoire et si vous voulez l’éditer, vous pouvez taper ‘vi const’, enfoncer la touche TAB, et le shell va remplir le reste du nom pour vous (à condition qu’il soit unique).
Bash vous montre la voie
Bash complète aussi bien les noms de commandes que les variables d’environnement. En cas de possibilités multiples de complétion, taper deux fois sur la touche TAB vous montrera toutes les complétions possibles. Bash est le shell par défaut de la plupart des systèmes Linux.
Redirection
grep chaine fichier > nouveau_fichier
redirige la sortie de la commande précédente ‘grep’ dans un fichier nommé nouveau_fichier. Si nouveau_fichier existe il sera remplacé/ecrasé
grep chaine fichier >> fichier_existant
ajoute la sortie de la commande ‘grep’ à la fin du fichier fichier_existant.
Les opérateurs de redirection > et >> peuvent être utilisés sur la sortie de la plupart des commandes, pour les placer dans un fichier.
Pipes
Le symbole tube (”pipe”) “|” est utilisé pour rediriger la sortie d’une commande vers une autre.
Par exemple :
ls -l | more
Cette commande prend la sortie du listage au format long des fichiers dans un répertoire produit par “ls -l” et la redirige vers la commande “more” (aussi appelé filtre). Dans ce cas, une très longue liste de fichier peut être vue page par page.
Substitution de Commande
Vous pouvez utiliser le résultat d’une commande comme paramètre d’entrée pour une autre, en d’autres termes pour une substitution de commande. Une substitution de commande a lieu lorsque vous encadrez une commande avec des apostrophes inversées. Par exemple :
cat `find . -name aaa.txt`
va afficher à l’ecran (voir cat) le contenu de tous les fichiers nommés aaa.txt dans le dossier de travail courant ou ses sous-dossiers.
Rechercher une chaîne de caractères : La commande grep
grep chaine fichier
affiche toutes les lignes de fichier contenant chaine
Rechercher des fichiers : La commande find
Syntaxe :
find chemin -name fichier
find . -name aaa.txt
cherche les fichiers nommés aaa.txt dans le dossier courant ou ses sous-dossiers.
find / -name vimrc
cherche les fichiers nommés vimrc depuis le dossier racine
find /usr/local/games -name "*xpilot*"
cherche tous les fichiers dont le nom contient xpilot dans le dossier /usr/local/games
Créer des archives : La commande tar
La commande tar signifie ‘tape archive’ (archive sur bande). C’est la méthode ’standard’ pour lire et écrire des archives.
Vous trouverez souvent des archives de fichiers avec des noms comme fichiers.tar, ou fichiers.tar.gz. Ce sont respectivement des fichiers dans une archive tar et des fichiers dans une archive tar qui a été compressée avec le programme de compression gzip.
Il est très probable, si quelqu’un vous envoie des fichiers, qu’ils soient compressés dans une archive tar.
De même, si vous devez envoyer des fichiers, vous devriez utiliser tar.
tar -xvf archive.tar |
extrait les fichiers de l’archive archive.tar, en affichant les noms des fichiers qui la composent |
tar -xvzf archive.tar.gz |
extrait les fichiers de l’archive en utilisant gzip puis tar |
tar -jxvf archive.tar.bz2 |
extrait les fichiers de l’archive en utilisant bzip2 puis tar |
tar -cvf archive.tar fichier1 [fichier2...] |
Crée un fichier “archive.tar” contenant fichier1, fichier2… |
tar -cvzf archive.tar.gz mon_dossier |
crée un fichier gzip contenant tout le contenu du dossier ‘mon_dossier’ |
Compression de fichier : gzip, bzip2
gzip
gzip est un outil GNU de compression et de decompression. L’extension pour les fichiers gzippés est .gz.
| gzip fichier.txt | crée le fichier compressé fichier.txt.gz |
| gunzip fichier.txt.gz | extrait le fichier fichier.txt |
bzip2
L’utilitaire bzip2 offre (en général) un meilleur taux de compression que gzip, mais au coût d’un temps de compression et décompression plus élevé.
| bzip2 fichier.txt | crée le fichier fichier.txt.bz2 |
| bunzip2 fichier.txt.bz2 | décompresse le fichier fichier.txt.bz2. |
Besoin d’aide : La commande man
La plupart des commandes ont une page de manuel qui donne une description de leurs utilisations plus ou moins détaillées, parfois utiles, parfois obscures. Certains disent qu’elles ont été appelées “man pages”, parce qu’elles ne s’adressent qu’aux vrais Hommes.
Exemple:
man ls
affiche la page de manuel pour la commande ls
Pour obtenir des man pages en français :
sudo apt-get install manpages-fr
Commandes de base de l’éditeur Vi
Ouvrir un fichier
vi nom_du_fichier
Mode édition
i : insère avant le curseur
I : Insère au début de la ligne courante
a : insère après le curseur
A : insère à la fin de la ligne
r : remplace 1 caractère
R : passe en mode Remplacement\
<ECHAP> : met fin au mode Edition (insertion ou remplacement)
Effacer du texte
x : efface un seul caractère
dd : efface la ligne courante et la place dans un buffer
ndd : Efface n lignes (n est un nombre) et les place dans le buffer
J : déplace la ligne suivante à la fin de la ligne courante (effacement des caractères de retour chariot)
Oups
u : annule la dernière commande
Copier et coller
yy : copie la ligne courante dans le buffer
nyy : copie n lignes dans le buffer (n est un nombre)
p : colle le contenu du buffer après la ligne courante
P : colle le contenu du buffer avant la ligne courante
Positionnement du curseur
gg : va en haut de la page
G : va en bas de la page
:n : positionne le curseur à la ligne n
:$ : positionne le curseur à la fin de la ligne
^g : affiche le numéro de la ligne
h,j,k,l : respectivement gauche, bas, haut et droite ; les flèches de direction fonctionnent aussi…
Recherche de chaîne de caractères
/chaîne: recherche “chaîne”. n permet le passage à l’occurrence suivante. # permet de passage à l’occurrence précédente.
*: recherche avant de la chaîne de caractères présente sous le curseur.
#: recherche arrière de la chaîne de caractères présente sous le curseur.
Substitution de chaîne de caractères
:n1,n2:s/chaîne1/chaîne2/[g][c] : substitue chaîne1 pour chaîne2 sur les lignes n1 à n2. Si g est indiqué (global), toutes les références de chaîne1 sont remplacées, sinon seule la première référence est remplacée. Si c est indiqué (confirm), une confirmation sera demandée avant chaque modification.
^ : méta-caractère de début de ligne
. : méta-caractère, vrai sur n’importe quel unique caractère sauf retour chariot
$ : méta-caractère de fin de ligne
Ces caractères, tout comme les autres caractères spéciaux, peuvent être ‘échappés’ à l’aide du \ : c’est-à-dire pour capturer la chaîne de caractères “/usr/STRIM100/SOFT”, il faut utiliser l’expression régulière “\/usr\/STRIM100\/SOFT”
Exemples:
:1,$:s/chien/chat/g
Remplace ‘chien’ par ‘chat’, pour chaque occurrence du fichier - de la ligne 1 à la fin du fichier ($)
:23,25:s/chien/chat/
Remplace ‘chien’ par ‘chat’ des lignes 23 à 25. Une fois par ligne, dès la première apparition.
Sauver, quitter et commandes d’exécution
Ces commandes sont toutes préfixées par les deux points (
et apparaissent dans le coin inférieur gauche de la fenêtre.
Vous ne pouvez pas saisir ces commandes en mode édition. Appuyer sur <ECHAP> pour sortir du mode édition
:w : enregistre le fichier (Write)
:w nouveau.fichier : enregistre le fichier sous le nom ‘nouveau.fichier’
:wq : enregistre le fichier et quitte le programme
:q : quitte
:q! : quitte sans enregistrer les changements
:e fichier : ouvre ‘fichier’ pour l’édition
:set number : affiche les numéros de ligne
:set nonumber : cache les numéros de ligne
:set noai : désactive l’auto-indentation
Source : dB or not dB ?
Ce document contient:
1 Introduction………………………………………………………………………………….
2 Why use decibels in our calculations? …………………………………………….
3 Definition of dB…………………………………………………………………………….
4 What about dBm? ………………………………………………………………………..
5 What’s the difference between voltage decibels and power decibels?…
6 What is a level?……………………………………………………………………………
7 Attenuation and gain …………………………………………………………………….
Series connection of two-port circuits: ………………………………………..
8 Conversion from decibels to percentage and vice versa ……………………
Converting % voltage to decibels and vice versa………………………….
Converting % power to decibels and vice versa …………………………
Converting % voltage more or less to decibels…………………………..
Converting % power more or less to decibels…………………………….
9 Using dB values in computations ………………………………………………….
Adding power levels ……………………………………………………………….
Measuring signals at the noise limit ………………………………………….
Adding voltages……………………………………………………………………..
Peak voltages………………………………………………………………………..
10 Just what can we measure in decibels?…………………………………………
Signal-to-noise ratio (S/N)……………………………………………………….
Noise……………………………………………………………………………………
Averaging noise signals ………………………………………………………….
Noise factor, noise figure ………………………………………………………..
Phase noise ………………………………………………………………………….
S parameters ………………………………………………………………………..
VSWR and reflection coefficient ………………………………………………
Field strength …………………&







