如何在MATLAB中从几个矩阵中选择随机样本?

时间:2017-02-17 16:27:42

标签: matlab matrix sampling

使用MATLAB,我有几个8760x1矩阵。我需要从第一个数据中随机选择一些数据,然后从其他矩阵中选择数据,但是从第一个数据中得到的数据位于同一位置,即

data1 = [a b c d e];
data2 = [f g h i j];

我是数据样本[a c d],然后我需要在此订单上选择[f h i],给我:

out1 = [a c d]
out2 = [f h i]

datasample是最好的工具吗?或者我该怎么办? 感谢。

4 个答案:

答案 0 :(得分:1)

Datasample会很好用,只要你使用非替换形式(我猜你不想重复输出。如果你对它有好处,那么忽略'替换&# 39;旗帜)。索引输出也将是未排序的,因此您可以完美地将其用于data2:

data1 = [a b c d e];
data2 = [f g h i j]
[out1,idx] = datasample(data1,k,'Replace',false);
out2=data2(idx);

我看到你还需要随机提取剩余的2760中的1500个,然后在第三个矢量上剩余的1260个。",你可以使用idx信息忽略该组:

idx_notused=setdiff(1:size(data1,1),idx); %finds all positions not selected previously
[out1_v2,idx2] = datasample(data1(idx_notused),k,'Replace',false); %k=1500
idx2=idx_notused(idx2); %so it maps with the original data
out2_v2=data2(idx2);

%and again for the remaining 1260:
idx_remaining=setdiff(1:size(data1,1),[idx idx2]);
out1_v3=data1(idx_remaining);
out2_v3=data2(idx_remaining);

答案 1 :(得分:0)

mat1 = [4, 3, 5, 4];
mat2 = [1, 1, 2, 2];

s = size(mat1);
[v] = randperm(s(2), 2); <--- remember the indices 


ret = mat1(v);
ret = [ret; mat2(v)];
enter code here


out1 = ret(1, 1:end);
out2 = ret(2, 1:end);

修改

[v] is a 1/0 vector which represents the places chosen to pick from values. 
now to choose from the data left, we need to extract the data not picked and  
pick from it.

v2 = (1-v);
TempMat = Mat(v2);

TempMat is the remaining data not picked in first place.

答案 2 :(得分:0)

我相信以下解决方案将满足您的需求。在向量k2中,你将有n个不同的索引用于你想要的矩阵。

k1=randperm(length(data1)); 
k2=k1(1:n)    % row of n samples
out1=data1(k2);
out2=data2(k2);

答案 3 :(得分:0)

对于不重复的采样,您可以使用randperm,即从“块”中的相同数据重新采样的事实。大约1500个元素,不会改变您重复的基本事实。因此,您只需重新排序所有数据,然后将其重塑为您想要的大小:

data1 = ('abcdewryt').';
data2 = ('fghijvbnm').';
k = 2; % samlpe size
N = 3; % no. of times to resample
rand_ind = randperm(size(data1,1)); % reorder all your data
out1 = reshape(data1(rand_ind(1:k*n)),[k,n]); % extract output from data1 in a shuffled order
out2 = reshape(data2(rand_ind(1:k*n)),[k,n]); % extract output from data2 in a shuffled order
left1 = data1(rand_ind(k*n+1:end)); % all what's left in data1
left2 = data1(rand_ind(k*n+1:end)); % all what's left in data2

现在,您在out的每列中都有来自数据的示例,并且您有N列用于重新采样数据N次。原始向量中剩下的所有内容都在left s。

结果的一个例子:

out1 =
ywb
det
out2 =
nvg
ijm
left1 =
a
r
c
left2 =
a
r
c