MATLAB: How to make vector by value and index

mapping index and valuevector

Hello, I try to make vector by value and index.
Please see my code.
Tk=(rand(1,k)*N0); % Tk is index of h, k is index number, N0 is maxmum index.
Tk=sort(Tk);
Ck=randn(1,k); %Ck is value matched index of Tk.
h=zeros(1,N0); % h is vector with index of Tk and value of Ck.(the other index has all zero.)
Example)
Tk = 2.2, 5.4
Ck = 44, 67
h = 0 0 ...0 0 0 44 0 0 0 0 0 ...0 67 0 0 0 0...
Please explain me.

Best Answer

Tk = randperm(N0, k); %k integers from 1 to N0, no need to sort them
Ck = randn(1,k);
h = zeros(1, N0);
h(Tk) = Ck;
This can be done in two lines as
h = zeros(1, N0);
h( randperm(N0, k) ) = randn(1, k);
I also recommend that for the future you read about randi()