I want to randomly select from a list of rows from a matrix to change the values
1 view (last 30 days)
Show older comments
I have a matrix B of 0's and 1's, and I have selected the rows and columns that contain the 1's. I now want to randomly choose some of these rows to change the value. I have a rate beta of how many of the rows I need to change. So I want the row and column numbers of the matrix that need to be changed, and then I need to change them. This is the code that I tried to use
B = [0,1,0;0,0,0;0,1,0]
beta = 0.6
[rows,cols]=find(B);
infInd=rows(randn(length(rows)))
0 Comments
Accepted Answer
Kevin Xia
on 27 Jul 2017
Try using randperm instead of randn. What randperm does is that it generates a random permutation from 1 to n. This can be useful for randomizing matrix indices. Please refer to the documentation of randperm for more details. Here is an example:
B = eye(5)
beta = 0.6;
[rows,cols]=find(B);
B =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
Use randperm to generate a random permutation from 1 to length(rows), which is in this case 5:
randRowIndices=randperm(length(rows))
randRowIndices =
5 3 2 1 4
It has been assumed that beta is the percentage of rows changed, 60%. Thus in this case, 3 rows in this case will be changed. Note that the function round is applied to make sure that numRowsChanged is an integer. One way to do this is to use vector indexing:
numRowsChanged=round(beta*length(rows));
rowChangeIndices=randRowIndices(1:numRowsChanged)
rowChangeIndices =
5 3 2
Thus, the 5th, 3rd, and 2nd rows will be changed. Use matrix indexing to change the B matrix:
B(rows(rowChangeIndices),cols(rowChangeIndices))=0
B =
1 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 Comments
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices 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!