MATLAB: Get certain matrix entries to a new matrix

looploopsMATLABmatrix manipulationr2020a

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.

Best Answer

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
>>