Do a cross-set operation on a matrix

I have a matrix which looks as follows:
[1 2 3;
4 5 6]
I want to do a cross-set operation on itself, so that each element is associated with every other element, like this:
[1 2 3;
4 2 3;
1 5 3;
4 5 3;
1 2 6;
4 2 6;
1 5 6;
4 5 6]
Can someone please help me/point me in right direction?

 채택된 답변

Sean de Wolski
Sean de Wolski 2012년 4월 10일

0 개 추천

A = [1 2 3; 4 5 6]; %data
[xx yy zz] = meshgrid(1:2,3:4,5:6); %column-wise linear indices
B = [A(xx(:)) A(yy(:)) A(zz(:))] %extract
More - generalized to n-dimensions and rows:
A = [1 2 3 7; 4 5 6 9]; %data
[nr nc] = size(A);
C = num2cell(reshape(1:(nr*nc),nr,nc),1);
X = cell(nc,1);
[X{1:nc}] = ndgrid(C{:}); %column-wise linear indices
for ii = nc:-1:1
V(:,ii) = A(reshape(X{ii},[],1));
end

댓글 수: 5

Vinay Pandey
Vinay Pandey 2012년 4월 10일
Can this be extended to matrix with 'n' number of columns?
Sean de Wolski
Sean de Wolski 2012년 4월 10일
sure.
Vinay Pandey
Vinay Pandey 2012년 4월 10일
What I mean to ask was, how can we extend it to n-columns, when we don't know the number of columns in advance.
Sean de Wolski
Sean de Wolski 2012년 4월 10일
see edit
Vinay Pandey
Vinay Pandey 2012년 4월 10일
Thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by