# MATLAB: Indexing problem in a script (“for” loop)

indexing

Hello,
I have a matrix A of dimension k x (d-1) and a matrix B of dimension m x (d-1).
I wish to compute an expression C = Sum from i=1 to i=d-1 of ( A(j,i)* (column number i of B) )
C will be a vector of length m, on which my script will then do other operations.
My problem is with the j index in A(j,i). I first considered a simple "for" expression, with "for j=1:k", but it does not match what i would like to obtain. In fact, I don't want each A(j,i) in each term of the sum to be with the same j. For example, in the first run, C will be obtained by summing : A(1,1)*column1ofB + A(1,2)*column2ofB + … + A(1,d-1)*column(d-1)ofB. With the simple "for" expression that I had considered, the second run would be : A(2,1)*column1ofB + A(2,2)*column2ofB + … + A(2,d-1)*column(d-1)ofB. Between those two runs, I would like to compute also the possibilities like the sum containing A(1,1), A(2,2), A(1,3)… and A(1,d-1) as well as for example the sum containing A(1,1), A(1,2), A(2,3)…and A(1,d-1). I would like to have all "permutations".
How could I implement that? Thank you very much!

#### Best Answer

• You are apparently allowing permutations with repetitions. If so, there will be a total of k^(d-1) of them. You can use 'dec2base' to generate them.
C = zeros(m,k^(d-1));for n = 1:size(C,2)  p = dec2base(n-1,k,d-1)-'0'+1;  C(:,n) = B * A(p(:)+k*(0:d-2)');end
The array C will have k^(d-1) columns, one for each possible "permutation" of the A rows.
You should be cautious about how large you make k and d. The number k^(d-1) can be surprisingly large. Also Mathworks has a limitation on the base k: it cannot exceed 36 and it must be at least 2. If you want other values of k, you will need to design your own replacement for 'dec2base'.