2 Column Matrix to 1 column Matrix

조회 수: 1 (최근 30일)
Hesham Ismail
Hesham Ismail 2015년 7월 26일
댓글: Azzi Abdelmalek 2015년 7월 26일
Hello,
I have this Matrix
2 4
4 11
5 7
5 10
7 12
8 10
11 12
2 8
I want the output to be something like this
2 4 11 12 7 5 10 8 2
So basically start with the first element 2 and build the connection. since 2 is connected to 4, and 4 is connected to 11, 11 is connected to 12, 12 is connected to 7 and so on. I am not sure how to program this in a simple way.
Another example to make it clear
1 2
2 3
3 6
6 1
to be changed to
1 2 3 6 1
Hope the question is clear.
  댓글 수: 3
Image Analyst
Image Analyst 2015년 7월 26일
편집: Image Analyst 2015년 7월 26일
OK, it looks like you're considering only numbers on the same row, then when a row is "used" you look for the number in a different row. What if the next number shows up in 5 rows? Which of the 5 rows do you pick next? What if there is a row that is not connected to anything prior? For example, what if row two had 991 and 999 in it? You'd never get to that row. There could be many such rows that are "unattached".
Hesham Ismail
Hesham Ismail 2015년 7월 26일
@image analyst Thanks these condition will be consider as a new row in the final output

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

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2015년 7월 26일
편집: Azzi Abdelmalek 2015년 7월 26일
a= [2 4
4 11
5 7
5 10
7 12
8 10
11 12
2 8];
test=0;
out=a(1,: );
d=a(2:end,:);
while test==0
[ii,jj]=find(d==out(end),1);
if ~isempty(ii)
out(end+1)=d(ii,setdiff(1:2,jj));
d(ii,:)=[];
else
test=1;
end
end
out
  댓글 수: 2
Hesham Ismail
Hesham Ismail 2015년 7월 26일
Thanks it works, is there a way to preallocate out variable in your code?
Azzi Abdelmalek
Azzi Abdelmalek 2015년 7월 26일
It's possible to pre-allocate the variable out to size(a,1), then take what we have to take. I tried it, but it doesn't improve the speed.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by