Reputation: 647
I am trying to implement neural network in c++ using armadillo
linear algebra library . I am using Cube
for storing inputs
and weights
of the network and I want to be able to add bias
unit in the 3d matrix. I came across many ways to do that which involve conversation from cube to matrix which seemed inefficient. So what is the most efficient way to add a column of zeros in the beginning of each matrix in the cube?
Upvotes: 3
Views: 1768
Reputation: 861
Unfortunately, join_slices
, only supports joining cubes with same number of rows and columns. Hence you need to loop through each slice and append a row-vector using insert_rows
, like so:
#include<armadillo>
using namespace arma;
uword nRows = 5;
uword nCols = 3;
uword nSlices = 3;
/*original cube*/
cube A(nRows , nCols, nSlices, fill::randu);
/*new cube*/
cube B(nRows+1, nCols, nSlices, fill::zeros);
/*row vector to append*/
rowvec Z(nCols, fill::zeros);
/*go through each slice and change mat*/
for (uword i = 0; i < A.n_slices; i++)
{
mat thisMat = A.slice(i);
thisMat.insert_rows(0, Z);
B.slice(i) = thisMat;
}
This should give:
A:
[cube slice 0]
0.0013 0.1741 0.9885
0.1933 0.7105 0.1191
0.5850 0.3040 0.0089
0.3503 0.0914 0.5317
0.8228 0.1473 0.6018
[cube slice 1]
0.1662 0.8760 0.7797
0.4508 0.9559 0.9968
0.0571 0.5393 0.6115
0.7833 0.4621 0.2662
0.5199 0.8622 0.8401
[cube slice 2]
0.3759 0.8376 0.5990
0.6772 0.4849 0.7350
0.0088 0.7437 0.5724
0.2759 0.4580 0.1516
0.5879 0.7444 0.4252
B:
[cube slice 0]
0 0 0
0.0013 0.1741 0.9885
0.1933 0.7105 0.1191
0.5850 0.3040 0.0089
0.3503 0.0914 0.5317
0.8228 0.1473 0.6018
[cube slice 1]
0 0 0
0.1662 0.8760 0.7797
0.4508 0.9559 0.9968
0.0571 0.5393 0.6115
0.7833 0.4621 0.2662
0.5199 0.8622 0.8401
[cube slice 2]
0 0 0
0.3759 0.8376 0.5990
0.6772 0.4849 0.7350
0.0088 0.7437 0.5724
0.2759 0.4580 0.1516
0.5879 0.7444 0.4252
Upvotes: 2