Matlab:通过索引数组删除struct值

时间:2014-06-17 17:25:37

标签: matlab struct

我有一个大型结构(总计),我需要将它分成3个结构,这些结构的值是从原始结构中随机选择的。我需要一个60%(trainingData)的结构,以及两个20%的结构(testData& crossValData),但没有一个值可以重叠。

indexRand1 = zeros((size(total,1)*.2),1); % index of test data: 20%
indexRand2 = zeros((size(total,1)*.2),1); % index of cross validation data: 20%

for index_i = 1:size(indexRand1,1)
    temp1 = randi([1 size(total,1)],1,1); % get a random value from total
    temp2 = randi([1 size(total,1)],1,1); % get another random value from total

    while ismember(temp1,indexRand1) % make sure 1st value is not already in test data
        temp1 = randi([1 size(total,1)],1,1);
    end
    indexRand1(index_i,1) = temp1; % add 1st value to test data

    while ismember(temp2,indexRand1) % make sure 2nd value is not already in test data
        temp2 = randi([1 size(total,1)],1,1);
        while ismember(temp2,indexRand2) % or cross validation data
            temp2 = randi([1 size(total,1)],1,1);
        end
    end
    indexRand2(index_i,1) = temp2; % add 2nd value to cross validation data
end
indexRand3 =[indexRand1;indexRand2]; % index of test and cross validation data 

testData = total(indexRand1,:); % use index to get test data
crossValData = total(indexRand2,:); % use index to get cross validation data
total(indexRand3,1) = []; % remove test and cross validation data
trainingData = total; % save training data to new name

我的问题来自'total(indexRand3,1)= []; %删除测试和交叉验证数据'我得到的错误是'空赋值只能有一个非冒号索引'。如何使用索引从结构中删除值? (或者如何将结构随机分成3个不相等的结构?)

1 个答案:

答案 0 :(得分:1)

我认为你正在使这个问题变得比它需要的更难。一个更Matlab-y的解决方案似乎是:

%Make some test data
%    (Well, I guess you already have data. I need data to test with) 
total(1000).sampleData = 1

%Determine the number of elements in each derived set
nTraining = round(numel(total)*0.6);
nTest     = round(numel(total)*0.2);
nCrossVal = numel(total) - nTest - nTraining;

%Create a random order vector
ixsRandomOrder = randperm(numel(total));

%Use the random order vector to create distinct, derived sets
testData     = total(ixsRandomOrder(                    (1:nTest)     ));
trainingData = total(ixsRandomOrder(nTest +             (1:nTraining) ));
crossValData = total(ixsRandomOrder(nTest + nTraining + (1:nCrossVal) ));