Hi everyone, I’m quite green in programming but I want to know how to change my code that generates ARRAY and divides every element by RAND_MAX number into code that generates MATRIX and divides every element by RAND_MAX number. I might imagine the whole algorithm but I don’t know for sure how exactly do it.
Here’s the code:
what exactly are you trying to do? It looks like you want a random array of floating point values, is that all you need here? <random> supports directly making floating point values without all the clutter. And why the C memory stuff? Is CUDA requiring your code to be in C only, and if so, C does not have cout / namespaces.
If its c++ and not c, vector is a type and best not reused as a variable name.
rand/randmax in floating point is just randoms from 0 to 1 in value heavily skewed (the average will be nowhere near 0.5). if you take a random number and put a decimal point in front of it, it will be closer if you care.
Thanks for your comment, Jonnin. What exactly I am trying to do is to generate random matrix e.g. (2x2 size) and each element of it divide by rand_max. I know how to do it with vector because it's just a single array but I don't have a clue how to do it with 2D array...
make a 2-d vector?
vector<vector<float> > twod; //avoid all that C memory stuff.
you can also map a 1-d vector as a 2-d and that has a ton of advantages.
vector[desired_row*number_of_cols + desired_col] lets you use a 1-d as if 2-d.
its easier to copy, construct and destruct, iterate, reshape, and more, and you can hide the computed indexing with a class wrapper if it bothers you.
The code you ask us to modify is so contrary to modern C++ that I doubt anybody here will give you more than the bread crumbs that @jonnin provided.
You are already mixing "C" (malloc, free) with "C++" (std::cout, <<). I highly recommend that you select one language and use it. As @jonnin suggested, use std::vector or std::array rather than dynamically allocating memory. And what is division<<<20,1>>>(gpu_vector,max,gpu_result_vector);? I can't figure out what that does at all.
If you insist on using this ugly, error-prone code, you will have to do your own research. Try googling "C++ multi-dimensional array" and see what you can learn from that.
And what is division<<<20,1>>>(gpu_vector,max,gpu_result_vector);? I can't figure out what that does at all.
This is not pure C++. CUDA provides a compiler that allows you to mix your kernels (GPGPU programs) with regular CPU code. The kernel in this case is the division() function. You can tell it's GPU code because it's prefixed with global. That line is calling into the GPU with the division function while passing the given parameters. The template-looking parameters specify parallelism constraints (I can't remember the specifics ATM, and it's not important either way).