indexing a vector in a loop

7 views (last 30 days)
Edward Levavasseur
Edward Levavasseur on 16 Aug 2018
Edited: Stephen23 on 16 Aug 2018
Hi,
I have 5, 3x1 column vectors:
A1 = [a11; a12; a13]
A2 = [a21, a22, a23]
...
A5 = [an1, an2, an3]
and I would to define new vectors X_abcde, by summing these 5 column vectors in all possible ways:
X00001 = A1
...
X00005 = A5
...
X00012 = A1 + A2
...
X00045 = A5 + A4
...
X00123 = A1 + A2 + A3
...
X00345 = A3 + A4 + A5
...
X01234 = A1 + A2 + A3 + A4
...
X02345 = A2 + A2 + A3 + A5
...
X12345 = A1 + A2 + A2 + A3 + A5
My only problem is that I don't know if it's even possible to index the vectors in the following way:
for i = 1 : 5
X0000`i' = A`i'
end
and then:
for i = 1:5
for j > i & j <= 5
X000`i'`j' = A`i' + A`j'
end
end
etc...
Is there any way that I can define a vector X000`i'`j', where `i' and `j' are the letters used in the for loop?
Thank you very much in advance!
  2 Comments
Rik
Rik on 16 Aug 2018
Yes, but you shouldn't. You should use an array (e.g. a cell array). Then your loop becomes way easier to write, Matlab will have a chance to optimize your code, code analysis tools like the m-lint will work and it will be easier to work with the result.
Stephen23
Stephen23 on 16 Aug 2018
Edited: Stephen23 on 16 Aug 2018
"My only problem is that I don't know if it's even possible to index the vectors in the following way:"
It is possible, but it is NOT recommended. Magically accessing variable names like that is how beginners force themselves into writing slow, complex, buggy code. Read this to know why:
See my answer for a much simpler and more efficient solution.

Sign in to comment.

Answers (1)

Stephen23
Stephen23 on 16 Aug 2018
Edited: Stephen23 on 16 Aug 2018
This is much simpler and more efficient that your idea of magically accessing variable names. I simply preallocate some cell arrays, use nchoosek to generate all of the combinations, and use each combination as basic indexing into the matrix of vectors:
N = 5; % number of vectors
M = randi(9,3,N); % N 3x1 vectors
C = cell(1,N);
for ii = 1:N
X = nchoosek(1:N,ii);
D = cell(2,size(X,1));
for jj = 1:size(X,1)
D{1,jj} = sum(M(:,X(jj,:)),2);
D{2,jj} = X(jj,:);
end
C{ii} = D;
end
C = [C{:}];
The first row of C gives the summed vectors, the second row gives the vector combination. Lets check some of the outputs:
>> M % five 3x1 vectors in one matrix
M =
5 2 5 1 9
8 5 9 9 1
4 1 4 2 6
>> C{:,1} % sum of vectors [1]
ans =
5
8
4
ans = 1
>> C{:,2} % sum of vectors [2]
ans =
2
5
1
ans = 2
>> C{:,6} % sum of vectors [1,2]
ans =
7
13
5
ans =
1 2
>> C{:,19} % sum of vectors [1,3,4]
ans =
11
26
10
ans =
1 3 4
>> C{:,31} % sum of vectors [1,2,3,4,5]
ans =
22
32
17
ans =
1 2 3 4 5

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!