I want to randomly select from a list of rows from a matrix to change the values

1 次查看(过去 30 天)
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)))

采纳的回答

Kevin Xia
Kevin Xia 2017-7-27
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 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by