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()
{
    start_time=time(0);
}

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
   
    toc();
    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?


References:
http://stackoverflow.com/questions/11085393/matlab-tic-toc-equivalent-in-c

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()
{
    FileVariable=1;
}

void SetToTwo()
{
    FileVariable=2;
}

int GetValue()
{
    return FileVariable;
}







int CheckCounter()
{

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

#endif




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


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

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

    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.



NOTE:
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
{
    private:
    int    m_nVal;  // just one integer variable
    float m_fVal; // just one float variable

   public:
   MyClass(int nVal, float fVal)   // constructor for this class
  {
     m_nVal=nVal;
     m_fVal=fVal;
  }

  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.


Example:
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.


NOTE
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"

Example.
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*"

NOTES:

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





NOTE:
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

NOTE:
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.


EXAMPLE:

>>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 =

    1.0500


bb =

     8



%%%%%%%%%%%%% 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
    x=x';
end

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

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

matrix=sortrows(matrix);

x_ii=matrix(1,2);
ii=find(x==x_ii);



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


os=lower(getenv('OS'));

if (isempty(findstr(os, 'windows')))
    %It's a unix system
    bar="/";
else
    % It's a Windows system
    bar="\";
end