How can I construct a matrix with its column elements as matrix operations?
1 view (last 30 days)
Show older comments
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
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?
Accepted Answer
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{:}];
More Answers (2)
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.
0 Comments
See Also
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!