How can I construct a matrix with its column elements as matrix operations?

1 view (last 30 days)
Hello everyone,
I want to construct a M X N matrix with results imported from other matrices.
For example, I have 3 matrices
I want to construct a matrix with first column input as A+B, second column as B+C and third column as C+A
----> Yellow column as A+B, Orange column as B+C, Blue column as C+A
Basically I want a matrix of all possible combinations. Please help me. Thank you.
Regards,
Azhar Uddin Mohammed
  3 Comments
Guillaume
Guillaume on 16 Nov 2014
That's not a particularly good idea.
Anyway, what's the naming pattern? and how do you know how many individual variables to combine?

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 16 Nov 2014
Assuming your column vectors are stored in cell array C:
combs = num2cell(nchoosek(1:numel(C), 2), 2);
S = cellfun(@(comd) C{comb(1)} + C{comb(2)}, combs, 'UniformOutput', false);
M = [S{:}];
Or, if your column vectors are actually columns of a matrix M1:
combs = num2cell(nchoosek(1:size(M1, 2), 2), 2);
S = cellfun(@(comb) sum(M1(:, comb), 2), combs, 'UniformOutput', false);
M2 = [S{:}];
  1 Comment
Azhar Uddin
Azhar Uddin on 27 Sep 2015
That is the perfect answer I wanted. Column vectors are actually columns of a matrix. But I need to know one more thing. Can I make the first row display the combination performed for any particular column. For example, first column is a combination of A+B, then A+B should appear in first row to make identification easy. Is it possible?

Sign in to comment.

More Answers (2)

the cyclist
the cyclist on 16 Nov 2014
Edited: the cyclist on 16 Nov 2014
Rather than storing the original variables as A,B,C; can you you store them as A{1}, A{2}, A{3}? If so, then it is easy:
M = 4;
N = 3;
% Make up some data
for nn = 1:N
A{nn} = rand(M,1);
end
% Preallocate memory
M = zeros(M,N*(N-1)/2);
% Combine
cc = 0;
for n1=1:N
for n2=n1+1:N
cc = cc+1;
M(:,cc) = A{n1}+A{n2};
end
end
It was not clear how the sorting should be in the general case, so you might need to adapt this.

Matt J
Matt J on 16 Nov 2014
Edited: Matt J on 16 Nov 2014
Assuming A,B, and C are column vectors,
S=[A,B,C];
S_new = S + circshift(S,[0,1]);

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!