How can I get randperm function to calculate assigned percentage and values?

1 回表示 (過去 30 日間)
종현 김
종현 김 2022 年 6 月 30 日
回答済み: Steven Lord 2022 年 6 月 30 日
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

採用された回答

Keshav
Keshav 2022 年 6 月 30 日
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

その他の回答 (1 件)

Steven Lord
Steven Lord 2022 年 6 月 30 日
Let's look at a slightly smaller problem.
A = zeros(10);
numElements = numel(A)
numElements = 100
numDesired = ceil(0.25*numElements)
numDesired = 25
elementsToSet = randperm(numElements, numDesired)
elementsToSet = 1×25
80 78 77 26 7 38 96 65 99 57 14 15 42 10 81 86 8 51 90 30 1 22 47 33 62
A(elementsToSet) = 1
A = 10×10
1 0 0 0 0 1 0 0 1 0 0 0 1 0 1 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 1 1 0 0 0 1 1 0 1 0 0 1 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 1 1 0
howManyNonzeroElements = nnz(A) % Should be numDesired
howManyNonzeroElements = 25
Alternately if you're working with sparse matrices you should look at sprand, sprandn, and sprandsym instead.

カテゴリ

Help Center および File ExchangeSparse Matrices についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by