# Randomly select one value from an Array.

3 Ansichten (letzte 30 Tage)
Refat Haj Mohamad All am 24 Jan. 2023
Kommentiert: Stephen23 am 25 Jan. 2023
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 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
Stephen23 am 25 Jan. 2023
"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))

Melden Sie sich an, um zu kommentieren.

### Antworten (2)

the cyclist am 24 Jan. 2023
Here is one way to pull 30 random values (with possible repeats) from A.
randomIndex = randi(200,30,1);
new_A = A(randomIndex)
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

Image Analyst am 24 Jan. 2023
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.
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by