Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Linearly Spacing Data in C

  1. Feb 21, 2010 #1
    For the use of linear and logarithmic interpolation, how can I produce linearly and logarithmically spaced arrays in C? I know in Matlab the code is

    A = linspace(a,b,c) or A = logspace(a,b,c)

    but how can I do this in C?
  2. jcsd
  3. Feb 21, 2010 #2
    You use a for loop, an initial value, and you increment by the the linear or log value you want, then place those values in the array (which is basically what matlab is doing in the background)

    basically some variant of:
    int spaced_array[NUMVALUES];
    int i=initial linear/log value;
    for (j=0; j<NUMVALUES; j++)
    i+=linear/log increment;
    Last edited: Feb 21, 2010
  4. Feb 22, 2010 #3
    Thanks for your help. I am having difficulties in understanding something else. If I have an initial value say log(2) and my final value of 10, and I want 12 logarithmically distributed samples, do I say is my step size going to be (10 - log(2))/12? I am kind of confused about how to implement this.

    And I assure you, this is not homework.
  5. Feb 22, 2010 #4
    float array[12];
    array[0] = log(2.0);
    float step = pow(10.0 / array[0], 1./11.);
    for(j=0; j<11; j++)
    array[j+1] = array[j] * step;
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook