Ordinare Righe Matrice In Modo Random

di Anonimizzato16754 il
3 risposte
Buonasera.
Vorrei chiedere se esiste un comando che mi permette di ordinare le righe di una matrice in modo random.

Ad esempio:

A=[1 2 3
4 5 6
7 8 9]

B=[4 5 6
1 2 3
7 8 9]

Quindi data la matrice A il mio comando deve riordinare le righe, matenendole inalterate, in modo random.

Grazie a tutti

3 Risposte

  • Per ordinare in modo random le righe di una matrice puoi usare la funzione randperm
    >> help randperm
    randperm Random permutation.
    P = randperm(N) returns a vector containing a random permutation of the
    integers 1:N. For example, randperm(6) might be [2 4 5 6 1 3].

    P = randperm(N,K) returns a row vector containing K unique integers
    selected randomly from 1:N. For example, randperm(6,3) might be [4 2 5].

    randperm(N,K) returns a vector of K unique values. This is sometimes
    referred to as a K-permutation of 1:N or as sampling without replacement.
    To allow repeated values in the selection, sometimes referred to as
    sampling with replacement, use RANDI(N,1,K).

    randperm calls RAND and therefore changes the state of the random number
    generator that underlies RAND, RANDI, and RANDN. Control that shared
    generator using RNG.
    Es:
    idx=1:10
    idx =
         1     2     3     4     5     6     7     8     9    10
    
    rand_idx=randperm(length(idx))
    rand_idx =
         5     6     9     7     4     1    10     8     2     3
    Nel caso specifico di riordinamento delle righe (o delle colonne) di una matrice è sufficiente determinare il numero di righe (o delle colonne) della matrice usando la funzione size e generare la sequenza random di indici:
    % Generazione di un matrice di esempio
    a=reshape(1:16,4,4).'
    % Determinazine della dimensione della matrice
    [n_righe,n_colonne]=size(a)
    % Riordinamento random delle righe della matrice
    b1=a(randperm(n_righe),:)
    % Riordinamento random delle colonne della matrice
    b2=a(:,randperm(n_colonne))
    
    a =
    
         1     2     3     4
         5     6     7     8
         9    10    11    12
        13    14    15    16
    
    n_righe =
         4
    
    n_colonne =
         4
    
    b1 =
        13    14    15    16
         1     2     3     4
         9    10    11    12
         5     6     7     8
    
    b2 =
         1     4     3     2
         5     8     7     6
         9    12    11    10
        13    16    15    14
    
    Hope this helps.
  • Simply the best

    ciao
  • E' stato un piacere
Devi accedere o registrarti per scrivere nel forum
3 risposte