How to fill in a zeroes matrix using data from a separate array.

13 views (last 30 days)
I am trying to work out how to fill in a matrix of zeroes to represent precedence requirements.
I have a 40x40 matrix of zeroes, and each collumn and row represent the tasks 1:40. I also have a 121x2 matrix with the precedent requirements. This is such that if a task needs to be completed before a different task can start, the first task is listed in collumn one and the second in collumn two.
I want to represent this in the form of having a matrix of 1s and 0s where a 1 is placed in row 1 collumn 2, it shows that task 2 relys on task one having happened. If there is a 0 there is no precedence requirement.
Is there a way i can take my 121x2 matrix and populate the 40x40 matrix accordingly? I assume it will be through a loop of reading each like of the 121x2 matrix and populating the 40x40 in this way but i wouldn't know how to approach the code for this.
Thank you in advance for any support.
  1 Comment
Dyuman Joshi
Dyuman Joshi on 9 Feb 2024
"Is there a way i can take my 121x2 matrix and populate the 40x40 matrix accordingly? "
Yes, you can use indexing to do that.
How you can utilize indexing will depend on the assignment is to be done.

Sign in to comment.

Accepted Answer

Matt J
Matt J on 9 Feb 2024
Edited: Matt J on 9 Feb 2024
Sounds like a job for accumarray, e.g,
requirements=[1 2; 2 3; 3 4; 4 6; 5 8]
requirements = 5×2
1 2 2 3 3 4 4 6 5 8
matrix = accumarray(requirements,1,[40,40])
matrix = 40×40
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

More Answers (1)

Voss
Voss on 9 Feb 2024
Here's one way to do that, demonstrated with smaller matrices:
% a 3x2 matrix of precedence requirements, in lieu of your 121x2 matrix, for simplicity.
% task 1 must be completed before task 2; 2 before 3; 3 before 4:
precedence = [1 2; 2 3; 3 4]
precedence = 3x2
1 2 2 3 3 4
% 4x4 matrix of zeros, in lieu of your 40x40 matrix, for simplicity
M = zeros(4,4)
M = 4x4
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
% put the 1s in place. this will work for your matrices too
idx = sub2ind(size(M),precedence(:,1),precedence(:,2));
M(idx) = 1
M = 4x4
0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!