Wednesday, December 18, 2013

Thursday, August 22, 2013

Matlab tic/toc functions in C++

For some applications (e.g. to test multithreading codes), it is extremely useful to have something like the Matlab tic/toc functions in you C++ program.

I will show you how to implement the tic() and toc() functions by using the ctime library.
Create a new header file (.h extension), called tic_toc.h with  the following content:

#ifndef TIC_TOC
#define TIC_TOC

#include <iostream>
#include <ctime>

// Just a static variable that will be visible only within this file

 static time_t start_time=time(0);

void tic()

void toc()
    time_t end_time=time(0);   
    std::cout<<"Elapsed time is "<<difftime(end_time, start_time)<<" seconds."<<std::endl;

#endif TIC_TOC

Now let's see an example on how to use this header file. Basically, the tic() and toc() functions must be within specific point in the main.
Excercise (a very simple one) how much time does it take to fill 1E8 entries into a vector of double?

Here is the code, stored in a file called test-tic_toc.cpp

/* ***  Testing tic toc *** */
#include "tic_toc.h"
#include <iostream>
#include <vector>

using namespace std;

int main()

  // Setting the time counter... tic();
 cout<<"Welcome to the test tic/toc program"<<endl;

 // Creating a vector of doubles (and size zero)    vector<double> v(0);
    for (int i=0; i<1E8; ++i)
        v.push_back(i); // fill the vector
    return 0;

That's it! Now...

On OSX and Linux, to compile and run the program, open a terminal, walk through the folder containing your code and type:

g++ -o a.out test-tic_toc.cpp; ./a.out

On my machine (Intel 2.66 GHZ Core 2 Duo from 2008), the output is:

Welcome to the test tic/toc program
Elapsed time is 3 seconds.

On Windows,  you should use VisualC++ Express and run the program from the prompt.

If something does not run, ASK YOURSELF:

1) Am I  in the correct folder?
2) Did I put the header file is in the same folder of my test-tic_toc.cpp file?

3) Do I have gcc on my machine?


Tuesday, July 16, 2013

The static keyword in C/C++ programming

I will use a very simple project made by 2 files: main.c and extra.h  and their contents are reported below:

/* ****** extra.h ************* */

#ifndef EXTRA_H
#define EXTRA_H

/* Declaration of the static variable with file scope */
static int FileVariable=100;

void SetToOne()

void SetToTwo()

int GetValue()
    return FileVariable;

int CheckCounter()

     /* Declaration of the static variable within the function body */
    static int nCounter=0;
    return nCounter;   


/* *** *** *** main.c *** *** *** */

#include <stdio.h>
#include "extra.h"

int main()
    printf("Testing the static keyword... \n");
    printf("FileVariable is %d \n", GetValue());
    printf("FileVariable is %d \n", GetValue());

    printf("Counter is %d \n", IncreaseCounter());

    return 0;

On Linux/Mac OS X, to compile the program with gcc and run it, use the command:

cc -o main.c; ./a.out

If you made everything properly, the output will be:

FileVariable is 1
FileVariable is 2
nCounter is 3

What happened?
In C/C++, the static keyword has two basic uses.

1) To limit the visibility of a function or variable to the current file. 
This is the case for the variable FileVariable which is visible only to  the functions defined in extra.h, i.e. SetToOne, SetToTwo, GetValue and IncreaseCounter.
Just to be clearer, if you already know what global varibles are, well, static variables are just like global variables but only within the file they are defined.

If you attept to to do use or modify FileVariable within the main.c, you'll get an ERROR!!!
Try it!

FileVariable=100;  /* does not work! */

The only way to allow the previous expression is to remove the keyword static. Doing so,  FileVariable becomes a global variable and you can modify it freely both in main.c and extra.h

2) To let a variable to survive even if the function having it terminates.
Is it clear to you why nCounter is 3?
Within main.c, we called function 3 times! Check it out!
Without the keyword static, the variable Counter would have been created and re-set to zero at each function call.
Try it!
Remove the keyword static  and re-run the program.

In C++ the static keyword can also be used within a class, as  a counter. In this case, the static variable must be public and must be initialized outside the class.

class MyClass
    int    m_nVal;  // just one integer variable
    float m_fVal; // just one float variable

   MyClass(int nVal, float fVal)   // constructor for this class

  static int Counter;  // Our  static counter


// Initialization of the static variable...
static MyClass::Counter=0;

Monday, July 15, 2013

C++ and gcc on Linux/Mac: How to set your custom directory to include header files

Your profile:
You are using OSX or Linux and you are writing some code in C/C++  compiling it with gcc...
how can you modify the path in which gcc looks for your header files?

Simply enough you have to modify two environment variables: C_INCLUDE_PATH and CPLUS_INCLUDE_PATH, for C and C++ respectively.

Suppose you want to add the directory /opt/local/include for a C++ project in this case:

export CPLUS_INCLUDE_PATH=${CPLUS_INCLUDE_PATH}:/opt/local/include

in a similar way you can modify the C_INCLUDE_PATH variable.

To make this modification permament for every new terminal session, the export line must be put into the hidden .bash_profile file in your home directory.

How to search files and folders with a given partial name in a terminal

If you are looking for a specific file or folder in your filesystem, you need to use the linux/mac/UNIX command find

Type in a terminal the following command:

find path -name "partial name"

Suppose, you want to run a search across the entire filesystem looking for a file called foo (or containing foo in its name), in this case your command becomes:

find / -name "*foo*"


1) If you really want to start the search from root, keep in mind that as normal user you could not access some directories, so put a sudo in front of the command to become superuser! :

sudo find / -name "*foo*"

2) If you start from root, your search will take some time....

3) You can save the results in a file called my_search.txt in this way:

sudo find / -name "*foo*"> my_search.txt

(the file my_search.txt will be created in your current directory,  the one you get with the command pwd)

Friday, July 5, 2013

From String to const char pointer or char array and... back!

You can operate on strings in C++ both via the string class or the old (i.e. C like) const char pointer.

Notes on string:

To use the class string you have to include the string header:
#include <string>

In addition, to avoid mentioning every time the std namespace, I use the using keyword:

using namespace std;

(without this instruction you'll need to type std::string variable_name instead of just string variable_name)

From char* or char array to string

This is easier

const char *pCh="foo char* ";  // pointer to const char

/* two possible conversion methods */ 
string strTemp(pCh);    // through constructor
string strTemp= pCh;   // through assignment operator

Since the strong similarity between pointers and arrays, the previous commands work also with char arrays...

char aCh="foo char[] "; 

/* two possible conversion methods */ 
string strTemp(aCh);    // through constructor
string strTemp= aCh;   // through assignment operator

From string to char*or char array

In this case, the conversion to the const char is very quick, while going to char array takes a bit longer... 

string to const char*

string strMyString="This is a string";  // creation of a string object

/* using the c_str() method of the string object*/
const char *pCh=str.MyString.c_str(); 

string to char array

/ *
In this case, we need:
 (1) to assign the correct size of the char array 
 (2) to copy the string to the char array (char after char or by using strncpy) 
 (3) a null character to terminate the char array.

string strMyString="This is a string";  // creation of a string object with size = 16!

/* using the size() method of the string object*/
char aCh[str.MyString.size()+1]; // the +1 is for terminating the char array with '\0', size=17!

// copying via the string strncpy...
strncpy(aCh, strMyString.c_str(), strMyString.size()); // SYNTAX: strncpy(destination, source, length)

// ... alternatively we can copy using a for loop:

for (int ii=0; ii<strMyString.size(); ii++)
     aCh[ii]=strMyString[ii];    //the loop stops at 15 and that's fine... we have copied 16 characters, since we started from 0!

// either way you use to copy the string, do not forget to add the null terminating character!

aCh[strMyString.size()]='\0';   // at position 16 in the char array

The trickiest part is always to take into account for the correct size of the char array, paying attention to the fact that in C/C++ arrays start at 0, not 1!!!

Wednesday, April 24, 2013

How to find the closest value in 1D array in Matlab

My function GetClosestValue  finds the closest value in the gives array with respect to the entered target value.


>>v=[1.0000   25.0000   26.0000   10.0000   25.0000   21.0000    8.0000    1.0500    2.0000];
>>[aa, bb]=GetClosestValue(v, 1.03)

aa =


bb =


%%%%%%%%%%%%% CODE %%%%%%%%%%%%%%%%

function [x_ii, ii]=GetClosestValue(x, x_T)
% [x_ii, ii]=GetClosestValue(x, x_T)
% x= 1D array
% x_T= target value
% x_ii  = final value
% ii   = index corresponding to the final value
% Find the closest value (x_ii) and index (ii) in the given array with respect to the entered target value (x_T)

[mm, nn]=size(x);

if nn>mm

matrix=[abs(x-x_T) , x];

% sorting with respect to the first column, i.e. to the absolute differences among x and x_T



Did you like this post?
Let me know!

Tuesday, February 12, 2013

Matlab: How to get the right bar for Windows and UNIX systems

Windows systems use the backslash bar "\" to separate folders in a path string, while, on the other hand, the normal slash "/" is the one used on Mac OS X/Linux (in general unix) systems.
Even if it's not a big deal since Matlab can handle it, I find it quite disturbing so I wrote this simple code to address the issue.

function [bar]=getbar
% [bar]=getos
% bar="/" for unix systems and bar="\" for Windows systems


if (isempty(findstr(os, 'windows')))
    %It's a unix system
    % It's a Windows system

Saturday, February 2, 2013

Python: how "range" really works

In this post, I gonna show you - with some very simply examples - how the python built-in function range works!

Let's start with the official official python help:


Help on built-in function range in module __builtin__:

    range([start,] stop[, step]) -> list of integers
    Return a list containing an arithmetic progression of integers.
    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
    When step is given, it specifies the increment (or decrement).
    For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
    These are exactly the valid indices for a list of 4 elements.

Basically the list of integers is built with the following simple rules:

1) The list starts with start, an optional parameter having 0 as its default value
3) The step of the elements is given by step, an optional parameter having 1 as its default value
2) The last element is ALWAYS smaller than stop!

If N indicates the overall number of elements in the list, each element a_i  is calculated according to the rule:

a_i = start + step*(i-1)

and the last element MUST be smaller than stop:

a_N = start + step *(N-1) < stop

as a consequence...

N  <1+ (stop-start)/step

The result of 1+(stop-start)/step can be an interger or decimal number doesn't matter. The important thing is that N is integer and smaller than 1+(start - start)/step

Understood? Let's see the examples!

1) What is the output for range(1,9,2)?


N<1+(stop-start)/step =1 + (9-1)/2=5 hence N=4! Indeed...

[1, 3, 5, 7]

2) What is the output for range(1,8,2)?

N < 1+(stop-start)/step =1 + (8-1)/2=4.5 hence N=4! Indeed...

[1, 3, 5, 7]

3) What is the output for range(9)?
start=0 [default]
step=1 [default]

N < 1+(stop-start)/step =1 + (9-1)/1=9 hence N=8! Indeed...

[0, 1, 2, 3, 4, 5, 6, 7, 8]

4) What is the output for range(9,3,-2)?

N < 1+(stop-start)/step =1 + (3-9)/(-2)=4 hence N=3! Indeed...

[9, 7, 5, 4]

N represents the TOTAL number of elements but python labels them starting from 0 and ending at (N-1)!

Wednesday, January 30, 2013

edufit: a Matlab data fitting interface

I love Matlab, it is a great software but its fitting tools are a bit disappointing for me (see cftool).
The problem in my case came from the need to fit many files... at once.

For this reason, I have developed a simple (about 2200 code lines)  Matlab GUI interface for fitting one-dimensional data. I named it edufit.
Basically it is "just" a graphical front-end that use the powerful and standard function nlinfit (through my modified version mod_nlinfit).

edufit is the best way to use Matlab for curve fitting with custom equations. Trust me!
Try it and give me your feedback!

  • Quick serial analysis
  • Determination of the error bars (half of the 95% confidence interval)
  • Hold parameters (thanks to mod_nlinfit)
  • Easy support for using custom models (i.e. userdefined fitting functions)
System requirements:
  • Matlab 7 or higher
  • nlinfit must be installed: check it by typing which nlinfit in the Matlab Command Window.  If you get the message 'nlinfit.m' is bad news.
  • edufit runs on Windows, Mac and Linux
  • dualcursor is an optional package you can use within edufit
  • edufit_v1 folder and the edufit user guide are available here.

Matlab, format type, cursors, dualcursor, curve fitting, import acquisition data, plot and fit, error bars, errors, confidence intervals, exponential function, custom equation, tool, free fitting program, Matlab cftool, nlinfit, nlinfit vs lsqcurvefit, hold parameters in Matlab

Related posts:
mod_nlinfit: modified version of nlinfit for holding parameters 

Sunday, January 13, 2013

The Unreasonable effectiveness of C

Today I read a very interesting post about C by Damien Katz and I thought it could be interesting for you as well.

"For years I've tried my damnedest to get away from C. Too simple, too many details to manage, too old and crufty, too low level. I've had intense and torrid love affairs with Java, C++, and Erlang. I've built things I'm proud of with all of them, and yet each has broken my heart. They've made promises they couldn't keep, created cultures that focus on the wrong things, and made devastating tradeoffs that eventually make you suffer painfully. And I keep crawling back to C."