【问题标题】:MATLAB: Using for loop to assign specific values in a vector to a new group/vectorMATLAB:使用 for 循环将向量中的特定值分配给新的组/向量
【发布时间】:2018-02-11 21:37:23
【问题描述】:

我正在查看神经网络训练数据,并有一个包含 250 名患者的向量平均分配到 10 个不同的组,命名为Icross。这意味着 25 名患者已被分配到第 1 组,另外 25 名患者被分配到第 2 组,等等。Icross 是一个 250x1 向量。

我想创建一个 for 循环,将患者分成测试和训练组,分别为 ItestItrain 向量。这意味着分配到组 1-5 的患者在Itest,6-10 在Itrain

对于我的输出,理想情况下,两个向量中都有 250 行数据作为输出,由 1 和 0 组成,表示它是否已分配到组中,具体取决于我查看的生成向量。但是,使用我创建的 for 循环只需为每个向量分配一个值 5。关于如何修改我的循环有什么建议吗?

for Icross = 1:5;
    Itest = Icross;
    Itrain = ~Itest;
end

理想输出:

Name    Value    
Itest = 250x1 logical
Itrain= 250x1 logical

我创建的 for 循环的输出:

Name    Value
Icross  5 (1x1double)
Itest   5 (1x1double)
Itrain  0 (1x1logical)

【问题讨论】:

  • Itest=randperm(repmat([0 1],1,125),250) 你可以吗? Ittrain=~Itest. (我是用手机写的)

标签: matlab for-loop vector


【解决方案1】:

问题在于您的循环在每次迭代中为同一个变量分配了一个新值。只是一个数字示例,因为我不知道您的基础数据是什么样的:

% A single vector containing all the patients...
patients = (1:250).';

% A 25-by-10 matrix representing the patients categorized into groups...
patients_grouped = reshape(patients,25,10);

% Two matrices, one for the training and one for the test:
test = reshape(patients_grouped(:,1:5),125,1);
train = reshape(patients_grouped(:,6:end),125,1);

如果您想将 250 名患者随机分成 10 组,事情会变得更加复杂。为此,以下代码应该可以解决问题:

% A single vector containing all the patients...
patients = (1:250).';

% Define the number of groups...
g = 10;

% Split the patients...
[n,m] = size(patients);
count = numel(patients) / g;
[~,idx] = sort(rand(n,1));
C = patients(idx,:);

patients_grouped = NaN(count,g);

for k = 1:g
    idx_k = ((k - 1) * count) + 1:(k * count);
    patients_grouped(:,k) = C(idx_k,:);
end

一旦您的患者被随机分组​​到10 类别中,就可以像这样获取定义他们属于测试组还是训练组的逻辑数组:

patients_1to5 = patients_grouped(:,1:5);
patients_test = ismember(patients,patients_1to5(:));
patients_train = ~patients_test;

【讨论】:

    【解决方案2】:

    如果Icross 是一个具有 1-10 值的向量,将患者分配到 10 个组中,那么

    Itest = Icross <= 5;
    

    对于第 1-5 组中的所有患者为真 (1),并且

    Itrain = ~Itest;
    

    其他组 (6-10) 中的所有患者都是如此。

    【讨论】:

      猜你喜欢
      • 2015-04-22
      • 1970-01-01
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2019-02-09
      • 2013-09-09
      相关资源
      最近更新 更多