Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply each element of an array by a number in C

I'm trying to optimize some of my code in C, which is a lot bigger than the snippet below. Coming from Python, I wonder whether you can simply multiply an entire array by a number like I do below.

Evidently, it does not work the way I do it below. Is there any other way that achieves the same thing, or do I have to step through the entire array as in the for loop?

void main()
{
    int i;
    float data[] = {1.,2.,3.,4.,5.};

    //this fails
    data *= 5.0;

    //this works
    for(i = 0; i < 5; i++) data[i] *= 5.0;

}
like image 458
seb Avatar asked May 24 '13 12:05

seb


2 Answers

There is no short-cut you have to step through each element of the array.

Note however that in your example, you may achieve a speedup by using int rather than float for both your data and multiplier.

like image 142
simonc Avatar answered Oct 22 '22 06:10

simonc


If you want to, you can do what you want through BLAS, Basic Linear Algebra Subprograms, which is optimised. This is not in the C standard, it is a package which you have to install yourself.

Sample code to achieve what you want:

#include <stdio.h>
#include <stdlib.h>
#include <cblas.h>
int main () {            
    int limit =10;
    float *a =  calloc( limit, sizeof(float));
    for ( int i = 0; i < limit ; i++){
        a[i] = i;
    }
    cblas_sscal( limit , 0.5f, a, 1); 

    for ( int i = 0; i < limit ; i++){
        printf("%3f, " , a[i]);
    }
    printf("\n");
}

The names of the functions is not obvious, but reading the guidelines you might start to guess what BLAS functions does. sscal() can be split into s for single precision and scal for scale, which means that this function works on floats. The same function for double precision is called dscal().

If you need to scale a vector with a constant and adding it to another, BLAS got a function for that too:

saxpy()
s      a x p y
float  a*x + y
y[i] += a*x

As you might guess there is a daxpy() too which works on doubles.

like image 26
cybrhuman Avatar answered Oct 22 '22 06:10

cybrhuman