How to index something based on numbering order???
조회 수: 2 (최근 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');
추가 답변 (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!