How can I get randperm function to calculate assigned percentage and values?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
종현 김
el 30 de Jun. de 2022
Respondida: Steven Lord
el 30 de Jun. de 2022
I need to calculate that out of 1000000 elements, 75% should be randomly assigned a value of 1.5.
‘p = randperm(n)’ to specify which element is assigned with the properties of inclusions, where ‘n’ is the total number of elements (1000000), ‘p’ contains randomly ordered numbers from ‘1’ to ‘n’. Then, I need to assign the first ‘m’ elements with the value (1.5)
Out of 1000000 elements, 75% should be randomly assigned a value of 1.5.
‘n’=1000000
‘m’=1.5
0 comentarios
Respuesta aceptada
Keshav
el 30 de Jun. de 2022
Based on my understanding, you want to generate an array of size n such that random 75% elements value is 1.5.
you can use the below code to do so.
n = 1000000;
p = randperm(n);
array = zeros(n,1);
num = .75*n;
for i = 1:num
array(p(i)) = 1.5;
end
% if you want you can assign some other value to the remaining elements
%for i = num+1:n
% array(p(i)) = some_other_val
%end
0 comentarios
Más respuestas (1)
Steven Lord
el 30 de Jun. de 2022
Let's look at a slightly smaller problem.
A = zeros(10);
numElements = numel(A)
numDesired = ceil(0.25*numElements)
elementsToSet = randperm(numElements, numDesired)
A(elementsToSet) = 1
howManyNonzeroElements = nnz(A) % Should be numDesired
Alternately if you're working with sparse matrices you should look at sprand, sprandn, and sprandsym instead.
0 comentarios
Ver también
Categorías
Más información sobre Sparse Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!