How to index something based on numbering order???
1 回表示 (過去 30 日間)
古いコメントを表示
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
0 件のコメント
採用された回答
Guillaume
2019 年 10 月 17 日
編集済み: Guillaume
2019 年 10 月 17 日
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 件のコメント
Guillaume
2019 年 10 月 17 日
A = A ./ sum(A, 2)
will normalise the rows of A so their sum is 1.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!