How to implement following in matlab?

1 回表示 (過去 30 日間)
Pramod Devireddy
Pramod Devireddy 2015 年 7 月 1 日
編集済み: Thorsten 2015 年 7 月 2 日
suppose I have a matrix:
A=[1 2;2 2;5 2;6 2;3 1;4 1]
I want the matrix: B=[1 2;1 5;1 6;2 5;2 6;5 6] in 1st iteration which are the combinations of first column elements of rows that have the second column as 2. and B=[1 3;2 3;5 3;6 3;1 4;2 4;5 4; 6 4;] in the second iteration which are the combinations of first column elements of rows that have the second column as 2 and 1. and B=[3 4] in the third iteration which are the combinations of first column elements of rows that have the second column as 1.
  2 件のコメント
dpb
dpb 2015 年 7 月 1 日
I can't figure out what your description means by comparing to the above B and A. Show us precisely the rule for the rearrangement.
Jan
Jan 2015 年 7 月 2 日
I do not understand the question.

サインインしてコメントする。

回答 (3 件)

Mark Matusevich
Mark Matusevich 2015 年 7 月 2 日
Make a function which gets a vector and creates all combinations, then call it 3 times:
B1 = combinations(A(1,A(:,2)==2));
B2 = combinations(A(1,ismember(A(:,2),[1 2])));
B2 = combinations(A(1,A(:,2)==1));
Implement the 'combinations' function using 'ndgrid' and
tril(ones(n,n),-1)
  1 件のコメント
Pramod Devireddy
Pramod Devireddy 2015 年 7 月 2 日
But i want the matrix B to change in iterations and i want to implement it for a bigger matrix in which the second column elements can start from higher number not just 2.

サインインしてコメントする。


Pramod Devireddy
Pramod Devireddy 2015 年 7 月 2 日
編集済み: Pramod Devireddy 2015 年 7 月 2 日
is there any way that i can improve it:
A=[1 2;2 2;5 2;6 2;3 1;4 1];
[svals,idx] = sort(A(:,2),'descend');
f=sort(unique(svals),'descend');q=1;m=[];
for i=1:size(f,1)
for k=q:size(f,1)
m=[m;f(i),f(k)];
end
q=q+1;
end
for j=1:size(m,1)
if m(j,1)==m(j,2)
B=combnk(A(idx((svals==m(j,1))),1),2)
else
B=combvec(A(idx((svals==m(j,1))),1)',A(idx((svals==m(j,2))),1)')'
end
end

Thorsten
Thorsten 2015 年 7 月 2 日
編集済み: Thorsten 2015 年 7 月 2 日
You can do this using nchoosek and ismember:
A = [1 2;2 2;5 2;6 2;3 1;4 1];
col2val{1} = 2;
col2val{2} = [1 2];
col2val{3} = 1;
B = A;
for i = 1:numel(col2val);
x = A(ismember(A(:,2), col2val{i}), 1)
if numel(x) < 2, break; end % cannot generate pairs of less than 2 numbers
pairs = nchoosek(1:numel(x), 2);
B = x(pairs)
end

カテゴリ

Help Center および File ExchangeView and Analyze Simulation Results についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by