You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matlab/Octave中按8:2比例拆分数据集为训练集和测试集?

Split Dataset into 80% Train / 20% Test in MATLAB/Octave

Hey there! Let's walk through how to create the logical indices idxTrain and idxTest you need—where training samples are marked as 1 and test samples as 0. This approach works seamlessly in both MATLAB and Octave.

Implementation Code

First, assuming you already have N = length(data.x) defined, here's the full, clean snippet:

% Calculate number of training samples (80% of total dataset)
numTrain = round(N * 0.8);

% Generate a random permutation of indices to avoid bias from original data order
permutedIdx = randperm(N);

% Initialize logical arrays with all false values
idxTrain = false(1, N);
idxTest = false(1, N);

% Mark the first 80% of permuted indices as training samples
idxTrain(permutedIdx(1:numTrain)) = true;

% Test set is the direct complement of the training set
idxTest = ~idxTrain;

Key Details & Practical Tips

  • Randomness & Reproducibility: Using randperm ensures your split is random each run. If you need consistent splits for debugging or comparison, set a random seed first with rng(42); (replace 42 with any integer of your choice).
  • Handling Non-Divisible Sample Counts: If N isn't a multiple of 5, round(N * 0.8) adjusts to the nearest integer. For strictly ≤80% training samples, use floor(N * 0.8); for strictly ≥80%, use ceil(N * 0.8).
  • Octave Compatibility: Every line here works in Octave without any syntax changes—randperm and logical operations behave identically across both platforms.

内容的提问来源于stack exchange,提问作者hello

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:07:46