Get certain matrix entries to a new matrix

조회 수: 3 (최근 30일)
Rene
Rene 2020년 8월 26일
댓글: dpb 2020년 8월 27일
Hello
I need to create a loop that reads certain data from a matrix and put it into a new matrix.
The matrix is for example:
2003 2004 0 0 0
2004 2005 0 0 0
2005 4005 0 0 0
3001 3002 5002 6002 0
Now I want to automatically create a new matrix that gives me all the "connections" like so:
2003 2004
2004 2005
2005 4005
3001 3002
3001 5002
3001 6002
Zeros should be ignored in the new matrix. The first column is always filled with a number.
Any idea how to do this? I'm thinking of a while loop but I can't figure out how.
  댓글 수: 2
tareq ALTALMAS
tareq ALTALMAS 2020년 8월 26일
can you please explain more
for example 2nd line how it became 2005 2005 and the last 2 lines also
Rene
Rene 2020년 8월 26일
편집: Rene 2020년 8월 26일
There was one mistake in the second matrix (as you saw with the 2005 2005).
The numbers are measurement points on a model. The first table/matrix gives the information which point connects to others.
Later all of the points will get x,y and z values to then plot a vector from point to point to get a 3d line model.
Therefore I need to extract the connections.
2003 connects to 2004 and no other
3001 connects to 3002, 5002 and 6002.
Is it any clearer now?

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

채택된 답변

dpb
dpb 2020년 8월 26일
Sometimes, just "dead ahead" is as good as any...
nAdd=sum(A~=0,2)-2; % number of connections beyond the one for each first node
V=zeros(size(A,1)+sum(nAdd),2); % preallocate for final array
% the engine...
j=0;
for i=1:size(A,1)
j=j+1;
V(j,:)=A(i,1:2);
for k=1:nAdd(i)
j=j+1;
V(j,:)=[A(i,1),A(i,2+k)];
end
end
above results in
>> V
V =
2003 2004
2004 2005
2005 4005
3001 3002
3001 5002
3001 6002
>>
  댓글 수: 3
dpb
dpb 2020년 8월 26일
You mean there's one or more nodes with a zero in column 2? If that's so, just remove them first...
A(A(:,2)==0)=[];
before the previous code.
Or after gets to same end but first is more efficient in reducing the size quicker.
dpb
dpb 2020년 8월 27일
Or, save only those w/ a node connection first...
A=A(A(:,2)~=0);

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by