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


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(range)

Help on built-in function range in module __builtin__:

range(...)
    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)?

start=1
stop=9
step=2

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

>>>>range(1,9,2)
[1, 3, 5, 7]

2) What is the output for range(1,8,2)?
start=1
stop=8
step=2

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

>>>>range(1,8,2)
[1, 3, 5, 7]


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

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

>>>>range(9)
[0, 1, 2, 3, 4, 5, 6, 7, 8]

4) What is the output for range(9,3,-2)?
start=9
stop=3
step=-2

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

>>>>range(9,3,-2)
[9, 7, 5, 4]

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




Features:
  • 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
Download
  • edufit_v1 folder and the edufit user guide are available here.


Keywords:
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."




Tuesday, November 27, 2012

Exercise 1-12 Write a program that prints its input one word per line

Kernighan & Ritchie - The  C  Programming Language (Second Edition)

Chapter 1

Exercise 1-12 Write a program that prints its input one word per line

This exercise is very interesting, because it gives you an important piece of information about how the input and output are read and stored.

The solution:


/*----------------------------------------------------------------*/
#include <stdio.h>
int main () {   


    int c;
    while((c = getchar()) != EOF)
    {
        if(c == ' ' || c == '\t' || c == '\n')
            putchar('\n');
        // flush the output!!!
        else
        // store the output!!!
            putchar(c);
       
    }

return 0;
/*----------------------------------------------------------------*/


So how this program really works?
In order to figure out, you have to know something that is NOT reported in K&R2.

Every time you type something into the console, this IS NOT read immediately by your program.
Instead, it is stored in a buffer memory until a special input is inserted!
This input is the newline.

The newline tells the Operating System (NOT YOUR PROGRAM) something like: "OK dude I typed everything I wanted and NOW pass it to my program so it can process it."

The same is also true for the output. Nothing really happens on the console until the special character '\n' is given to the operating system.

If you have understood my highly informal explanation, now you should be able to figure out how my solution works.

You type all your text, including words, tabs, blanks and, eventually, you press ENTER on your keyboard.

When the Operating System receives the newline command, it sends everything to your program that is now able to process, character by character, all your input.

During the processing, every character that is NOT a blank, a tab or a newline, is stored in a buffer for future release to the console. On the other hand, when the program encounters a blank, a newlines or a tab it gives the command ENTER to the operating system, that flushes ALL the content that has been stored previously in the buffer.

That's it.

For more information, please refer to A. Koenig and B.E. Moo - Accelerated C++ Practical Programming be Example - Chapter 1.


As always, if you like this post .... consider to offer me a coffee ;)