Adding elements from a matrix to different vectors in a loop
Show older comments
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
@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.
Accepted Answer
More Answers (1)
Guillaume
on 10 May 2017
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);
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!