MATLAB中corr函数计算Spearman相关性报索引错误,求解决
问题描述
相关代码
Rm = corr(timeModel, 'Type', 'Spearman'); Rm %First row of Rm contains the correlation coefficients between the values of avgExcTime and the expected execution times for all the possible values of KEY3:0 Rc = Rm(1,2:17); %The entry of Rc with the highest positive value corresponds to the guessed %key (the first entry of Rc is 1 and corresponds to the autocorrelation of %avgExcTime, therefore is discarded) [corr,idx] = max(Rc); guessedKeyNibble = idx-1
运行报错
Index in position 1 is invalid. Array indices must be positive integers or logical values.
Error in Part3 (line 60)
Rm = corr(timeModel, 'Type', 'Spearman');
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
已知timeModel尺寸为16×17,请问该如何修复?
修复方案
这个错误的核心是Matlab的corr函数调用逻辑或环境有问题,给你几个针对性的解决步骤:
排查是否有自定义函数覆盖系统
corr
在Matlab命令行输入which corr,如果返回的不是统计工具箱的默认路径(比如显示用户自定义文件夹下的corr.m),说明你写的同名脚本/函数覆盖了系统自带函数。解决方法是把自定义的corr.m重命名,或者移出Matlab的搜索路径。修正
corr的调用维度(匹配你的业务逻辑)
你的注释提到要计算第一行(avgExcTime)和其他行的相关系数,但默认corr是计算列与列的相关性。如果要计算行与行的相关,需要先转置矩阵,同时补充参数确保处理所有数据:% 转置后计算行(原矩阵的列)之间的斯皮尔曼相关 Rm = corr(timeModel', 'Type', 'Spearman', 'Rows', 'all');这样得到的
Rm是17×17的矩阵,第一行正好对应原timeModel第一行和所有行的相关系数,和你后续的索引逻辑匹配。验证
timeModel的有效性- 输入
whos timeModel确认变量类型是double,没有混入字符串、空值等非数值内容; - 如果矩阵里有NaN值,用
'Rows','all'(保留所有行)或'Rows','complete'(只保留无NaN的行)参数处理,避免corr返回空矩阵导致后续索引错误。
- 输入
内容的提问来源于stack exchange,提问作者IOT-Guy
相关产品推荐
相关产品推荐

