Multiply each element of the array by a number in C

I am trying to optimize part of my C code, which is much more than below. Based on Python, I wonder if it is possible to simply multiply the whole array by a number, as shown below.

Obviously, this does not work the way I do it below. Is there another way that achieves the same thing, or do I need to go through the entire array, as in a 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; } 
+4
source share
4 answers

No brevity, you need to go through each element of the array.

Note that in your example, you can achieve acceleration by using int rather than float for your data and multiplier.

+7
source

If you want, you can do what you want with BLAS , basic linear algebra routines that are optimized. It is not in the C standard, it is a package that you must install yourself.

Sample code to achieve the desired result:

 #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 are not obvious, but by reading the recommendations, you can begin to guess what the BLAS functions do. sscal() can be divided into s for single precision and scal for scale , which means this function works with floats. The same function for double precision is called dscal() .

If you need to scale a vector with a constant and add it to another, BLAS also got a function:

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

As you can guess, there is daxpy() , which works on doubles .

+6
source

I am afraid that in C you will have to use for(i = 0; i < 5; i++) data[i] *= 5.0; . Python allows so many shortcuts; however, in C, you need to access each element and then manipulate these values.

Using for-loop will be the shortest way to accomplish what you are trying to do with an array.

EDIT: if you have a large amount of data, there are more efficient (in terms of runtime) ways of multiplying 5 by each value. For example, loop through a loop.

+1
source
 data *= 5.0; 

Here, data strong> is the address of the array, which is constant. if you want to multiply the first value in this array, use the * operator, as shown below.

 *data *= 5.0; 
-2
source

Source: https://habr.com/ru/post/1482558/


All Articles