【问题标题】:MatLab: Index Exceed Matrix DimensionMatLab:索引超过矩阵维度
【发布时间】:2012-09-25 02:29:16
【问题描述】:

我有以下10折实现,我使用UCI Machine learning发布的数据集,这是数据集的链接:

Here are my dimensions

x = 

      data: [178x13 double]
    labels: [178x1 double]

这是我遇到的错误

Index exceeds matrix dimensions.

Error in GetTenFold (line 33)
    results_cell{i,2} = shuffledMatrix(testRows ,:);

这是我的代码:

%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

【问题讨论】:

  • 与其给你提供任何答案,我认为给你一些关于如何自己解决这个问题的建议要好得多。学习使用调试器。在 Matlab 命令提示符下键入 dbstop if error。这将导致 Matlab 在发生错误时进入调试器。在调试器中,您在函数内部,可以访问其中定义的所有变量。因此,在调试器中,键入 max(testRows) 和 size(shuffledMatrix,1) 之类的内容。这已经告诉你出了什么问题。输入dbcont 尝试继续,或输入dbquit 退出调试器。
  • 谢谢我是数学实验室的新手,但我不知道当我在另一个 150 X 4 的数据集上运行它时,它没有任何问题。

标签: matlab matrix machine-learning dimension


【解决方案1】:

您正在循环遍历1:numberOfRowsPerFold:dataRowNumber,这是1:x:178 和i 每次递增。因此,您可以在results_cell 上获得index out of bounds 错误。

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

学习调试

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    相关资源
    最近更新 更多