C++ return array from function

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++?

Topic weight-initialization c logistic-regression machine-learning

Category Data Science


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)


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

}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.