# [Rcpp-devel] a variable for loop

Wed Dec 14 07:24:18 CET 2016

```Hello Avraham --Happy to see you

My code is trying to produce a cube c which is going to be constructed by a
vector a and matrix b.
And the number of rows in b and size of a must be same.

So we can assume that if a is a vector of size 3, Then b must be 2 x 3 or 3
X 3 etc.

Thank you Avraham for quick response. I hope this will make my question
more clear.

Best regards

On Wed, Dec 14, 2016 at 4:46 PM, Avraham Adler <avraham.adler at gmail.com>
wrote:

> On Tue, Dec 13, 2016 at 9:51 PM, Amina Shahzadi <aminashahzadi at gmail.com>
> wrote:
>
>> Hello Friends and Prof. Dirk
>>
>> I am pasting here a code which has a for loop depending on another for
>> loop.
>> I am getting zeros for cube c. I tried and searched a lot but did not get
>>
>>
>> using namespace Rcpp;
>> using namespace arma;
>> //[[Rcpp::export]]
>>
>>
>> arma::cube  exam(arma::vec a,  arma::mat b)
>> {
>>   int m = a.size();
>>   int n = b.n_rows;
>>   arma::cube c = zeros<cube>(n, m, n);
>>   for(int i=0; i<n; i++) {
>>     for(int j=0; j<m; j++) {
>>       for(int k=0; k<i; k++) {
>>           if(k==0) {
>>             c(i, j ,k) = c(i, j, k) + b(i, j);
>>           }
>>           else{
>>             c(i, j, k) = c(i, j, k) +  c(i-1, j, k) *b(i, j);
>>           }
>>          }
>>         }
>>       }
>>   return c;
>> }
>>
>>
>> Thank You
>> --
>>
>
>
> Hello.
>
> I haven't run your code, but it strikes me that I cannot see where are you
> capturing the number of columns of b. It's a bit confusing as I was always
> taught a matrix has m rows and n columns. Be that as it may, your k==0 loop
> looks like it's trying to copy over the original matrix to the first slice,
> but how do you know that b has m columns, which is what you're assuming by
> letting j loop to m. Unless you are assuming a square matrix?
>
> Even if you are, if your matrix is not the same length as your vector, I
> think there is an issue with your loop boundaries, unless I've
> misunderstood something, which is certainly possible.
>
> For example, assume a is {1, 2, 3} and b is the 2 x 2 of row 1: [1 2] and
> row 2: [3 4]. Thus m = 3 and n = 2.
>
> Step 1: i = j = k = 0: c(0, 0, 0) becomes b(0, 0) or 1.
>
> Step 2: i = 0, j = 1, k = 0: c(0, 1, 0) becomes b(0, 1) or 2.
>
> Step 3: i = 0, j = 2, k = 0: c(0, 2, 0) becomes b(0, 2) ?!?! There is no
> b(0, 2), it's only a 2x2 matrix?
>
>
> Similar to your previous questions, instead of posting code, can you
> please describe in words what it is you are trying to do? That may help.
>
> Avi
>
>

--