# Randomly select one value from an Array.

조회 수: 11(최근 30일)
Refat Haj Mohamad All 2023년 1월 24일
댓글: Stephen23 2023년 1월 25일
I have a 200x1 Cell Array, A, and I need to randomly select x values from that cell array. I tried using randperm in a loop but it seems to select the values in order from Array A. Also repetition is permitted.
for i=1:30
new_A=A(randperm(i))
end
##### 댓글 수: 1표시숨기기 없음
Stephen23 2023년 1월 25일
"I tried using randperm in a loop but it seems to select the values in order from Array A."
That is how you wrote your code. The correct way to use RANDPERM() would be without a loop:
newA = A(randperm(200,30))

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

### 답변(2개)

the cyclist 2023년 1월 24일
Here is one way to pull 30 random values (with possible repeats) from A.
randomIndex = randi(200,30,1);
new_A = A(randomIndex)
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

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

Image Analyst 2023년 1월 24일
No loop needed. Try this to get x cells randomly chosen from a cell array, A, of any dimensions
randomIndexes = randi(numel(A), x, 1); % Linear indexes
output = A(randomIndexes); % Extract the cells into a new cell array.
Because we're using randi() instead of randperm(), it's possible to have some cells repeated in the output.

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

### 범주

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!

Translated by