Eigen::MatrixXd initialisation - eigen3

Actually my question is really simple, I'm looking for the most efficient way to construc vector (or ma) from a loop.
In Matlab we do : M = [1:10] how to do the same thing in Eigen ?

Thanks chtz, this is actually exactly what I want, so M=[1:10] in matlab is equivalent in C++ using Eigen to :
Matrix<double,Dynamic,1> M; //or VectorXd M
M = VectorXd::LinSpaced(9,1,10); // M.setLinSpaced(9,1,10)

Related

Eigen QR decomposition results differs from two methods

I try to use QR decomposition using Eigen, but the results get from the following tow methods is different, please help me to find out the error!
Thanks.
// Initialize the sparse matrix
A.setFromTriplets(triplets.begin(), triplets.end());
A.makeCompressed();
//Dense matrix method
MatrixXd MatrixA = A;
HouseholderQR<MatrixXd> qr(MatrixA);
MatrixXd Rr = qr.matrixQR().triangularView<Upper>();
//Sparse matrix method
SparseQR < SparseMatrix < double >, COLAMDOrdering< int > > qr;
qr.compute(A);
SparseMatrix<double, RowMajor> Rr = qr.matrixR();
This is because SparseQR performs column reordering to both reduce fill-in and achieve a nearly rank-revealing decomposition, similar to ColPivHouseholderQR. More precisely, HouseholderQR computes: A = Q*R, whereas SparseQR computes: A*P = Q*R. So it is expected that the two R triangular factors are different.

Elementwise product between a vector and a matrix using GNU Blas subroutines

I am working on C, using GNU library for scientific computing. Essentially, I need to do the equivalent of the following MATLAB code:
x=x.*(A*x);
where x is a gsl_vector, and A is a gsl_matrix.
I managed to do (A*x) with the following command:
gsl_blas_dgemv(CblasNoTrans, 1.0, A, x, 1.0, res);
where res is an another gsl_vector, which stores the result. If the matrix A has size m * m, and vector x has size m * 1, then vector res will have size m * 1.
Now, what remains to be done is the elementwise product of vectors x and res (the results should be a vector). Unfortunately, I am stuck on this and cannot find the function which does that.
If anyone can help me on that, I would be very grateful. In addition, does anyone know if there is some better documentation of GNU rather than https://www.gnu.org/software/gsl/manual/html_node/GSL-BLAS-Interface.html#GSL-BLAS-Interface which so far is confusing me.
Finally, would I lose in time performance if I do this step by simply using a for loop (the size of the vector is around 11000 and this step will be repeated 500-5000 times)?
for (i = 0; i < m; i++)
gsl_vector_set(res, i, gsl_vector_get(x, i) * gsl_vector_get(res, i));
Thanks!
The function you want is:
gsl_vector_mul(res, x)
I have used Intel's MKL, and I like the documentation on their website for these BLAS routines.
The for-loop is ok if GSL is well designed. For example gsl_vector_set() and gsl_vector_get() can be inlined. You could compare the running time with gsl_blas_daxpy. The for-loop is well optimized if the timing result is similar.
On the other hand, you may want to try a much better matrix library Eigen, with which you can implement your operation with the code similar to this
x = x.array() * (A * x).array();

Symbolic computation with formulas and solver

I am looking for a programming language and a way to automatize the following problems.
Given a formula connecting different variables, say g=GM/r^2, and values for all but one of the variables, (g=9.8,M=5E25,G=6.7E-11), how can I program a routine which:
a) Identifies the unknown variable
b) symbolically, solves the formula
c) finally, substitutes values of known variables and solves the equation for the unknown.
I am far from an expert in programming and the only thing it came to my mind was a slow process in which, one checks variable after variable which one has not been set to a value and according to that use the appropriate rearrangement of the formula to calculate the unknown.
(eg. in our case, the program checks variable after variable until it find that r is the unknown. Then, it uses the same formula but ready to calculate r, i.e. r=sqrt(GM/g))
I am sure there is a fast an elegant language to do this but I cannot figure it out.
Thanks in advance for your help.
Well, here is one way to do it, using Maxima.
eq : g = G * M / r^2;
known_values : [g = 9.8, M = 5e25, G = 6.7e-11];
eq1 : subst (known_values, eq);
remaining_var : listofvars (eq1);
solve (eq1, remaining_var);
=> [r = -5000000*sqrt(670)/7, r = 5000000*sqrt(670)/7]
You can use the function float to get a floating point value from that.
You can probably also do it with Sympy or something else.
For such a simple case, the approach that you suggest is quite appropriate.
The "slow" process might take on the order of 10 nanoseconds to find the unknown variable (using a compiled language), so I wouldn't worry so much.
Indeed symbolic computation programs are able to derive the explicit formulas, that you can retranscript in most programming languages
g=GM/r²
G=gr²/M
M=gr²/G
r=√GM/g
// C code
if (g == 0) g= G * M / (r * r);
else if (G == 0) G= g * r * r / M;
else if (M == 0) M= g * r * r / G;
else r= Math.sqrt(G * M / g);
For instance, the free Microsoft Mathematics can do it. But in this particular case, just do it by hand.
For a completely integrated solution with built-in scripting, think of Mathematica, Mathcad, Maple and the like.

Smart and Fast Indexing of multi-dimensional array with R

This is another step of my battle with multi-dimensional arrays in R, previous question is here :)
I have a big R array with the following dimensions:
> data = array(..., dim = c(x, y, N, value))
I'd like to perform a sort of bootstrap comparing the mean (see here for a discussion about it) obtained with:
> vmean = apply(data, c(1,2,3), mean)
With the mean obtained sampling the N values randomly with replacement, to explain better if data[1,1,,1] is equals to [v1 v2 v3 ... vN] I'd like to replace it with something like [v_k1 v_k2 v_k3 ... v_kN] with k values sampled with sample(N, N, replace = T).
Of course I want to AVOID a for loop. I've read this but I don't know how to perform an efficient indexing of this array avoiding a loop through x and y.
Any ideas?
UPDATE: the important thing here is that I want a different sample for each sample in the fourth (value) dimension, otherwise it would be simple to do something like:
> dataSample = data[,,sample(N, N, replace = T), ]
Also there's the compiler package which speeds up for loops by using a Just In Time compiler.
Adding thes lines at the top of your code enables the compiler for all code.
require("compiler")
compilePKGS(enable=T)
enableJIT(3)
setCompilerOptions(suppressAll=T)

convert a Matlab code into C code

I'm trying to understand and learn the C language, and since I used to work in Matlab, I'm interested in knowing how this code would be converted into C.
for j=1:n
v=A(:,j);
for i=1:j-1
R(i,j)=Q(:,i)'*A(:,j);
v=v-R(i,j)*Q(:,i);
end
R(j,j)=norm(v);
Q(:,j)=v/R(j,j);
end
Do you know about the Matlab Coder? Matlab can automatically generate c/c++ code for you. It has its limitations, but if are trying to learn c from Matlab, using the coder should be the best way for you to populate many examples.
Arrays are declared and accessed like so:
const int N = 10; // needs to be a constant
double v[N]; // 1-d
double A[N][N]; // 2-d
v[0] = A[1][2]; // indexing starts at 0, not 1
C doesn't do automatic vectorization like matlab, so you have to do it in for-loops manually. Instead of R(i,j)=Q(:,i)'*A(:,j),
for (int k = 0; k < N; ++k) {
R[i][j] += Q[k][i] * A[k][j];
}
That last piece also demonstrates what a for-loop looks like - the first "argument" of the "for" is the initialization of the indexing variable k, the second sets the condition under which the for loop continues, and the third increments k. The code to be executed in the loop is enclosed in braces {}.
The main logical difference is that you have to do everything element-by-element in C.

Resources