Adding elements from a matrix to different vectors in a loop

I have a 58x58 matrix consisting of ones and zeros which represent task precedence of different tasks. What I would like to do is to extract the positions of the ones in the matrix and adding it to two different vectors in order to get the precedence of which tasks are preceded by which and which are not. Hence, extract information into a vector showing the tasks which has precedence and a vector showing the task it must precede. What I have been trying so far is the following, represented by the code below:
%%Random matrix of ones and zeroes
n = 450;
p = zeros(58, 58);
p(randperm(numel(p), n)) = 1;
clear n
%%Loop to get precendce
q=1;
for i=1:size(p)
if p(i)>0
pp(q)=i;
q=q+1;
end
end
So, what I have done so far is that I have created the vector showing the first precedence relationship regarding task 1, but I still need the vector to include all other columns and create another vector replicating the task, so that I get something like this:
pp = [5;8;3;4;5;6;10;20;13;11;55]
pq = [1;1;2;2;3;4; 4; 4; 5; 6; 7]
The question is of course, how do I get my looping to do this?

댓글 수: 2

ROSN
ROSN 2017년 5월 10일
편집: ROSN 2017년 5월 10일
I solved it myself with the following code:
%%Random matrix of ones and zeroes
n = 450;
p = zeros(58, 58);
p(randperm(numel(p), n)) = 1;
clear n
%%Loop to get precendce
q=1;
[rowsize,colsize] = size(p);
for i=1:colsize
for j=1:rowsize
if p(i,j)==1
pp(q)=i;
qp(q)=j;
q=q+1;
end
end
end
To add, the tic denoted q is also the sum of total constraints within the matrix which again could be used to calculate for instance the
Stephen23
Stephen23 2017년 5월 10일
편집: Stephen23 2017년 5월 10일
@ROSN: this is much more complicated than it needs to be (nested loops, ifs, temporary variables), and will be quite inefficient as it expands both output arrays during the loop iterations:
In any case in my answer I gave you a much simpler and more efficient solution using just one command.

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

 채택된 답변

Stephen23
Stephen23 2017년 5월 10일
편집: Stephen23 2017년 5월 10일
You do not need the loops, just use find:
[qp,pp] = find(p.');

추가 답변 (1개)

Guillaume
Guillaume 2017년 5월 10일
I don't really understand the meaning of your two vectors but a much simpler way of obtaining the exact same info would be just one line:
[qp, pp] = find(p.'); %tranpose to match row-major sorting of qp and pp
And if the ordering doesn't matter (you're using row-major ordering whereas matlab is column-major), then this is even simpler:
[pp, qp] = find(p);

댓글 수: 1

Yeah I was not able to find that function in the beginning, so my guess was to loop. Transposed or not - it does not make a difference. Nevertheless, thank you for your feedback.

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

카테고리

도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2017년 5월 9일

편집:

2017년 5월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by