Danint
Danint

Reputation: 23

for loop for scalar product with a matrix

I'm trying to fill a 10 x 1500 matrix with a loop. I have to fill that matrix with 150 small 10 x 10 matrixes. I have tried to implement this with a double loop, but unsuccessfully. My problem is that each 10*10 matrix is the result of a scalar product. At the begin it seems to be easy, but then I realized I couldn't figure out the sizes of the 10 x 1500 matrix with the 150 small 10*10 matrixes. Here is what I did:

es_var is a 1 x 150 matrix, which I converted to a vector to simplify the scalar product (at least in my opinion). diax is a 10 x 10 matrix. I want to multiply each value of the es_var vector per the whole diag 10*10 matrix. I am having troubles because I don't manage to input R in filling 10 rows per time. Thus in the end I get a 10*1500 matrix, but it is the same 10*10 time matrix repeated 150 times.

Here is my code

es_var1 = as.vector(es_var)

v = matrix(0, 10, 10*N)

for (i in 1:N){
      v[,] = es_var1[i] * diax
}

Can somebody help in figuring out this, please? I spent the whole day trying it. And I need to do that without using in build functions since this is a small part of a big math demonstration I have to implement.

Upvotes: 2

Views: 416

Answers (1)

bgoldst
bgoldst

Reputation: 35314

If I understand your requirement correctly, you can accomplish this with the following line:

v <- matrix(diax,10,1500)*rep(es_var1,each=100);

This constructs a 10x1500 matrix with the 10x10 diax matrix as the initial values, cycled sufficiently to cover the complete 10x1500 size. Then, to apply the es_var1 multiplication, you can replicate each of its elements 100 times, such that they will naturally align with each consecutive 10x10 small matrix during vectorized multiplication.

Upvotes: 1

Related Questions