Say I have a matrix, v1, how would I be able to randomly generate 10 numbers within the existing matrix?

댓글 수: 2

Do you mean that you have, for example, a 5x5 matrix such as
M = magic(5)
M = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
and you want to select 10 numbers from that matrix at random?
Can you select the same number twice, or all 10 should be from a different position?
How do you want the output? A vector of 10 numbers?
For you future reference, please understand that if you had spent more writing out a more complete, thoughtful question, we would not need to clarify what you need.
Ashante Isabella Bon
Ashante Isabella Bon 2021년 9월 27일
Yes to first question, all different positions, Just 10 numbers no need to be a vector

댓글을 달려면 로그인하십시오.

 채택된 답변

Image Analyst
Image Analyst 2021년 9월 23일

0 개 추천

To generate the numbers from random locations, without repeating any of the locations you need to use randperm(), not randi() like other answer(s). Using randi() will potentially allow the same location to be used multiple times. So use randperm() or randi() depending on what you want.
% Generate sample matrix -- a 7 row-by-9 column matrix.
m = randi(100, 7, 9)
% Get 10 random linear indexes with no location being a repeat:
randomIndexes = randperm(numel(m), 10)
% Extract data at those random locations:
extractedNumbers = m(randomIndexes)

추가 답변 (1개)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 9월 23일

0 개 추천

Based on what you've stated the following could be what you want to obtain:
v1 = randi(10, 5, 5) %#ok % Is existing matrix
v1 = 5×5
2 5 2 1 10 7 5 3 1 6 10 4 4 1 9 2 6 5 3 1 8 5 2 10 2
IDX = randi([1, 10], 1, 10); % Randomly select indexes from the existing matrix
R = v1(IDX) % Randomly selected 10 numbers from v1
R = 1×10
4 5 5 10 8 5 8 5 2 8

카테고리

도움말 센터File Exchange에서 Random Number Generation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by