How to index something based on numbering order???

3 visualizzazioni (ultimi 30 giorni)
Hi everyone
I am not that much professional in Matlab and I have a vector of x= 94*1 containig 7 different integer numbers (1 to 7). I want to generate another vector Y= 94*7 of random numbers between 0 and 1 and put them as a vector based on the number in the x vector. I will explain how...
for example if the first number in the vector x is 2, okay, that means the first row in the generated vector Y should be [0.02 0.82 0.0025 0.03, 0.0027, 0.0025 0.0015] the most imprtant thing is the all generated numbers should be between 0 and 1, and the max number should be located in the place of the number in the vector x.
this id the input: x = [2; 3; 7; 5; 1]
the expected output is: Y =
0.0200 0.8200 0.0025 0.0300 0.0027 0.0025 0.0015
0.0024 0.0035 0.7600 0.0080 0.0500 0.0014 0.0020
0.0200 0.0025 0.0300 0.0027 0.0250 0.0015 0.8900
0.0024 0.0035 0.0080 0.0500 0.8400 0.0020 0.0027
0.9120 0.0002 0.0050 0.0258 0.0020 0.0010 0.0000
Thanks in advance

Risposta accettata

Guillaume
Guillaume il 17 Ott 2019
Modificato: Guillaume il 17 Ott 2019
Here is one way:
%input
x = [2; 3; 7; 5; 1]
%generate random matrix without worrying about the order
A = rand(size(x, 1), max(x));
%find current location of max of each row:
[~, col] = max(A, [], 2);
%convert col and x to linear indices, which will indicate which elements to swap
source = sub2ind(size(A), (1:size(A, 1))', col);
dest = sub2ind(size(A), (1:size(A, 1))', x);
%swap current max with its intended location
A([source, dest]) = A([dest, source]);
Note that if you are on R2019a or later, with the 'linear' option for max, you can replace the two lines:
[~, col] = max(A, [], 2);
source = sub2ind(size(B), (1:size(A, 1))', col);
by
[~, source] = max(A, [], 2, 'linear');
  4 Commenti
Gadelhag M Omar Mohmed
Gadelhag M Omar Mohmed il 17 Ott 2019
Hi Guillaume
Thank you, it is working as I want now. One more little question please, If I want to do the same process, but I want to have the total sum of the generated numbers that we generated in (A = rand(size(x, 1), max(x));) to be 1. So, I want the sum of these random numbers is 1.
Regards
Guillaume
Guillaume il 17 Ott 2019
A = A ./ sum(A, 2)
will normalise the rows of A so their sum is 1.

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by