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 个评论

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.

请先登录,再进行评论。

 采纳的回答

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

更多回答(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 个评论

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 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by