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.
Prashant Kumar answered .
2025-11-20
To fill a zero matrix with data from a separate array in MATLAB, you can use indexing. Here’s a clear guide on how to achieve this:
Example Code:
% Initialize the zero matrix
zeroMatrix = zeros(5, 5);
% Data array
dataArray = [1, 2, 3, 4, 5];
% Positions to fill (linear indexing example)
positions = [1, 7, 13, 19, 25];
% Fill the zero matrix with data
zeroMatrix(positions) = dataArray;
% Display the result
disp(zeroMatrix);
Explanation:
- Initialization: A 5x5 zero matrix is created.
- Data Array: The array containing the data to be inserted is defined.
- Positions: The positions in the zero matrix where data should be inserted are specified.
- Filling the Matrix: The data from the `dataArray` is assigned to the specified positions in the zero matrix.
Using this method, you can efficiently fill a zero matrix with data from a separate array based on your desired positions.