creating weighted sample for a matrix

조회 수: 7 (최근 30일)
Sophia
Sophia 2012년 5월 8일
편집: Michele Pio Papasidero 2021년 4월 26일
I need to create a sample from an m by n matrix. Each row has a probability associated with it and can be treated as one observation. I need to draw N (the sample size) number of these rows based on their assigned probability. The problem is that randsample only takes a vector as input such as this example:
R = randsample([1 2 3], N, true, [0.5 0.25 0.25])
Whereas I need something like this:
R = randsample([1 2 3; 4 5 6; 7 8 9], N, true, [0.5 0.25 0.25])
So far I've not found an answer from Google, so I'd appreciate any pointers.

채택된 답변

Sophia
Sophia 2012년 5월 9일
Thanks Sean, I figured it out. I add a unique ID to the first column of the sample matrix (route_sample) and perform randsample on that; then I use the FIND function to pull the actual sample values in.
%create random exogenous demand sample
R_tmp = randsample(route_sample(:,1),N,true,route_sample(:,8));
R_demand = zeros(N,size(route_sample,2)-2);
for i = 1:size(R_tmp,1);
[r1,~,~] = find(R_tmp(i,1)==route_sample(:,1));
R_demand(i,:) = route_sample(r1,2:7);
end;
  댓글 수: 1
Michele Pio Papasidero
Michele Pio Papasidero 2021년 4월 25일
편집: Michele Pio Papasidero 2021년 4월 26일
Dear Sophia, i have a similar issue (https://it.mathworks.com/matlabcentral/answers/812345-weighted-random-sampling-for-matrix). I tried to adapt this code to my situation but it does not work. Can you help me?

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Sean de Wolski
Sean de Wolski 2012년 5월 8일
(Unless I'm missing something (which is certainly possible (probable))) This could easily be done with a for-loop.

Community Treasure Hunt

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

Start Hunting!

Translated by