MatLab:索引超出矩阵维度

add*_*ons -1 matlab machine-learning matrix dimension

我有以下10折实现,我使用UCI机器学习的数据集发布,这是数据集的链接:

Here are my dimensions

x = 

      data: [178x13 double]
    labels: [178x1 double]
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误

Index exceeds matrix dimensions.

Error in GetTenFold (line 33)
    results_cell{i,2} = shuffledMatrix(testRows ,:);
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

%Function that accept data file as a name and the number of folds
%For the cross fold
function [results_cell] = GetTenFold(dataFile, x)
%loading the data file
dataMatrix = load(dataFile);
%combine the data and labels as one matrix
X = [dataMatrix.data dataMatrix.labels];
%geting the length of the of matrix
dataRowNumber = length(dataMatrix.data);
%shuffle the matrix while keeping rows intact 
shuffledMatrix = X(randperm(size(X,1)),:);

crossValidationFolds = x;
%Assinging number of rows per fold
numberOfRowsPerFold = dataRowNumber / crossValidationFolds;

crossValidationTrainData = [];
crossValidationTestData = [];
%Assigning 10X2 cell to hold each fold as training and test data
results_cell = cell(10,2);
    %starting from the first row and segment it based on folds
    i = 1;
    for startOfRow = 1:numberOfRowsPerFold:dataRowNumber
        testRows = startOfRow:startOfRow+numberOfRowsPerFold-1;
        if (startOfRow == 1)
            trainRows = (max(testRows)+1:dataRowNumber);
        else
            trainRows = [1:startOfRow-1 max(testRows)+1:dataRowNumber];
            i = i + 1;
        end
        %for i=1:10
        results_cell{i,1} = shuffledMatrix(trainRows ,:);
        results_cell{i,2} = shuffledMatrix(testRows ,:); %This is where I am getting my dimension error
        %end
        %crossValidationTrainData = [crossValidationTrainData ; shuffledMatrix(trainRows ,:)];
        %crossValidationTestData = [crossValidationTestData ;shuffledMatrix(testRows ,:)];
    end
end
Run Code Online (Sandbox Code Playgroud)

Gun*_*uyf 6

你遍历1:numberOfRowsPerFold:dataRowNumber这是1:x:178i每递增一次.所以这是一种可以解决index out of bounds错误的方法results_cell.

获取错误的另一种方法是testRows选择超出范围的行shuffledMatrix.

学习调试

要在发生错误时暂停代码并开始调试,请dbstop if error在执行代码之前运行.这样,编译器在遇到错误时进入调试模式,您可以在事情陷入混乱之前检查变量的状态.

(要禁用此调试模式,请运行dbclear if error.)