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 Comments

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

Sign in to comment.

 Accepted Answer

You do not need the loops, just use find:
[qp,pp] = find(p.');

More Answers (1)

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 Comment

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.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 9 May 2017

Edited:

on 10 May 2017

Community Treasure Hunt

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

Start Hunting!