Combination of vectors to build a matrix
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Marcell Magalhaes Oliveira
am 5 Okt. 2015
Bearbeitet: Stephen23
am 5 Okt. 2015
I have 10 column vectors with 4 elements each. I need do build a 4x4 matrix with different combinations of 4 of those vectors.
Example:
V1 = [2;4;2;1];
V2 = [3;3;5;1];
V3 = [4;1;2;1];
V4 = [7;8;1;1];
V5 = [5;4;2;1];
V6 = [1;8;7;1];
V7 = [3;2;0;1];
V8 = [9;8;1;1];
V9 = [1;4;7;1];
V10 = [2;1;5;1];
First 4X4 matrix combination should look like this:
M1 = [V1 V2 V3 V4];
Second 4X4 matrix combination should look like this:
M2 = [V1 V2 V3 V5];
I need a code to give me all the possible matrix with 4 different vectors.
Thank you!
2 Kommentare
Stephen23
am 5 Okt. 2015
Bearbeitet: Stephen23
am 5 Okt. 2015
Creating collections of numbered variables is usually a really bad idea.
You should store these vectors inside one matrix, and use indexing instead. Although beginners often seem to believe that using numbered variables are a great idea and will solve all of their problems, it is really very poor programming and will lead to practices that make your code buggy and slow, read this to know why:
Here is a discussion of why it is a bad idea to include meta-data (such as an index) in a variable name:
Although most beginners ignore this advice, please read those links and understand why it is a bad practice.
Akzeptierte Antwort
Guillaume
am 5 Okt. 2015
Bearbeitet: Guillaume
am 5 Okt. 2015
As per Stephen's answer do not use numbered variables. As all your vectors are the same size, you could all store them as rows of a single matrix. If you don't like that, you could store the vectors as elements of a cell array.
%direct conversion of your code. Not the most elegant way of generating the cell array
V{1} = [2;4;2;1];
V{2} = [3;3;5;1];
V{3} = [4;1;2;1];
V{4} = [7;8;1;1];
V{5} = [5;4;2;1];
V{6} = [1;8;7;1];
V{7} = [3;2;0;1];
V{8} = [9;8;1;1];
V{9} = [1;4;7;1];
V{10} = [2;1;5;1];
Once you've got your vectors in a cell or matrix, it's easy to generate all possible combinations of rows/vectors: use nchoosek.
vectorcombinations = nchoosek(1:numel(V), 4); %all combinations of 4 vector indices out of however many there are
You can then use the indices to create your matrices. You can use a loop iterating over the rows of vectorcombinations, or more advanced techniques such as cellfun:
allmatrices = cellfun(@(c) [V{c}], num2cell(vectorcombinations, 2), 'UniformOutput', false);
The important bit in the line above is just [V{c}], where c is the content of just one row of vectorcombinations. This just concatenates the 4 vectors referred by the indices of that row.
1 Kommentar
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!