简体   繁体   English

索引超过矩阵尺寸

[英]Index exceeds matrix dimensions

X= [P(1,:,:);
    P(2,:,:);
    P(3,:,:)];
y= P(4:end,:);
indTrain = randperm(4798);
indTrain = indTrain(1:3838);
trainX= X(indTrain,:);
trainy = y(indTrain); 
indTest = 3839:4798;
indTest(indTrain) = []; 
testX = X(indTest,:);
testy = y(indTest);

It shows error in trainX= X(indTrain,:); 它显示trainX= X(indTrain,:); saying

Index exceeds matrix dimensions 索引超过矩阵尺寸

can anyone pls clarify ? 有人可以澄清吗? thanks. 谢谢。

by the way I am having a 4x4798 data which my first 3 rows serve as predictors, and last row (4th row) is my response. 顺便说一下,我有一个4x4798数据, 4x4798行用作预测变量,最后一行(4th row)是我的响应。 how would i correctly split the data into the first 3838 columns as my training set and remaining as testing set. 我将如何正确地将数据分为前3838 columns作为我的训练集,并保留为测试集。

Thanks..!! 谢谢..!!

Fix your error 解决错误

To fix the indexing error you need to select the column indices of X , rather than the row indices: 要解决索引错误,您需要选择X索引,而不是索引:

trainX = X(:, indTrain );  

Some words of advice 一些建议

It seems like your P matrix is 4-by-4798 and it is two dimensional. 这似乎是你的P矩阵是4×4798,它是二维的 Therefore, writing P(1,:,:) does select the first row, but it gives the impression as if P is three dimensional because of the extra : at the end. 因此,在编写P(1,:,:)不选择第一行,但它给人的感觉仿佛P三维多余的,因为:在最后。 Don't do that . 不要那样做 It's bad habit and makes your code harder to read/understand/debug. 这是一个坏习惯,使您的代码更难以阅读/理解/调试。

X = P(1:3,:); % select all three rows at once
y = P(4,:); % no need for 4:end here - again, gives wrong impression as if you expect more than a single label per x.

Moreover, I do not understand what you are trying to accomplish with indTest(indTrain)=[] ? 此外,我不理解您要使用indTest(indTrain)=[]来完成什么工作? Are you trying to ascertain that the train and test set are mutually exclusive? 您是否要确定火车和测试仪是互斥的?
This line will most likely cause an error since the size of your test set is 960 and indTrain contains 1:3838 (randomly permuted) so you will get "index exceeds..." error again. 这行很可能会导致错误,因为测试集的大小为960,并且indTrain包含1:3838(随机排列),因此您将再次收到“索引超出...”错误。
You already defined your indTrain and indTest as mutually exclusive, no need for another operation. 您已经将indTrainindTest定义为互斥的,不需要其他操作。 If you want to be extra careful you can use setdiff 如果要格外小心,可以使用setdiff

indTest = setdiff( indTest, indTrain );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM