0
$\begingroup$

I would like to implement machine learning algorithm in C++ without using any C++ machine learning library. So I'm writing this initializer function for generating zero matrices but can't figure out how can I accomplish this. I'm actually trying to write C++ code for simple logistics regression for now.

float * intializer_zero(int dimension){
    // z = wx + b. 

float b = 0;
float w[dimension]= { };
return w,b;
}

It's throwing error "cannot convert 'float' to 'float' in return." How can I write this initializer function in C++?

$\endgroup$
  • 1
    $\begingroup$ Do you have knowledge of c++ ? Because c++ functions can't return more than one object. It should be good if you don't have c++ background to first learn the language $\endgroup$ – Jérémy Blain Oct 22 '18 at 13:22
  • $\begingroup$ Long time I've no contact with C++. So yes I'm not very familiar with C++. $\endgroup$ – Rouh Al Noor Auritro Oct 22 '18 at 13:23
0
$\begingroup$

you can use vector from the Standrad library to store your matrix in a variable way.

#include<vector>

Then you defined your function to initiliaze it to 0

void fill_zero( std::vector<std::vector<float>> &matrix, int row, int column)
{
    for(int i = 0; i<row; ++i)
    {
        std::vector<float> vector(column,0);
        matrix.push_back(vector);
    }
}

this fill a row x column matrix with 0. As matrix is passed by reference (& matrix) you need a c++11 compiler (I think). Same for the 'auto' keyword.

then you just need to create the matrix before calling the function

std::vector<std::vector<float>> matrix;
fill_zero(matrix);

//this is just for printng the matrix to see if it match your requirement !    
for(auto vector : matrix)
{
    for(auto value : vector)
    {
        std::cout<<value<<" ";;
    }
    std::cout<<std::endl;
}

I didn't test this an my own compiler, but it works here : C++ Shell compiler with the code above, if you want to test it ! (it fill it with ones instead of zeroes, it's just to be sure that the compiler doesn't initiliaze value of vector to 0 by default. That way I am sure that the function work as we want to)

$\endgroup$
  • 1
    $\begingroup$ Sorry for the late reply. Thanks a lot. It works perfectly and I understand it clearly. $\endgroup$ – Rouh Al Noor Auritro Oct 31 '18 at 23:37
0
$\begingroup$

You can do something like that for matrix

mat = new float*[rows];

for (ushort i = 0; i < rows; i++) {
    mat[i] = new float[cols](); //init 0

}

$\endgroup$
  • $\begingroup$ I think this is best to avoid C-style array $\endgroup$ – Jérémy Blain Oct 22 '18 at 14:40
  • $\begingroup$ @JeremyBlain this way is much faster $\endgroup$ – fwf May 3 '19 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.