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

MATLAB数组索引报错:起始行非1时出现索引越界问题

问题排查:MATLAB索引越界错误(star_row非1时触发)

我需要从8950行数据中提取指定范围(star_row到end_row)的分组数据,但当star_row不从1开始时,代码触发索引越界错误,无法定位问题。

报错代码行

plot(time_a(star_row:end_row),acceleration(star_row:end_row,2),'b','LineWidth',1.5);

完整代码

%D1

close all;

acceleration=gpu_load(1:end,:);
N = size(acceleration,1);
star_row = 3762 ;
end_row = N ;

test = acceleration(star_row:end_row,2).^2;
% non_zero number
non_zero = acceleration(acceleration(star_row:end_row,2) ~= 0, 2);
[dec_max, dec_max_idx] = max((acceleration(star_row:end_row,2).^2).^0.5);
[dec_min, dec_min_idx] = min((non_zero.^2).^0.5);
% GPU average
dec_avg = mean(non_zero);
time_a = (acceleration(star_row:end_row,1)-acceleration(1,1))/10^9;
time_satr = 1;
time_end = size(time_a,1);

figure
hold on
plot(time_a(star_row:end_row),acceleration(star_row:end_row,2), 'b','LineWidth',1.5);
plot(time_a(dec_max_idx),acceleration(dec_max_idx,2), '^r','MarkerSize',10);
plot(time_a(dec_min_idx),acceleration(dec_min_idx,2), '^r','MarkerSize',10);

h1 = legend('GPU usage',sprintf('Maximum GPU Usage = %0.3f', dec_max),sprintf('Minimum GPU Usage = %0.3f', dec_min), sprintf('Mean GPU Usage = %0.3f', dec_avg));
set(h1,'FontSize',15);
set(gca,'FontSize',15);

xlabel('Time (Sec)','FontSize',15,'FontWeight','bold');
ylabel('GPU usage','FontSize',15,'FontWeight','bold');

axis([star_row end_row 0 150]);
hold off
grid on

报错信息

Index exceeds the number of array elements. Index must exceed 5189.

Error in draw (line 23)
plot(time_a(star_row:end_row),acceleration(star_row:end_row,2), 'b','LineWidth',1.5);

排查与修复建议

  • 核心错误原因:time_a是从acceleration(star_row:end_row,1)截取计算得到的数组,长度为end_row - star_row + 1(示例中为8950-3762+1=5189)。但代码中用原数组的大索引star_row:end_row去访问缩短后的time_a,必然超出数组边界。

  • 针对性修复步骤:

    1. 修正主曲线的plot语句:time_a已经是截取后的时间序列,直接使用全量索引即可,无需额外范围限制:
      plot(time_a, acceleration(star_row:end_row,2), 'b','LineWidth',1.5);
      
    2. 修正极值点的索引映射:dec_max_idx和dec_min_idx是截取后数组的局部索引,访问原acceleration时需要加上偏移量star_row-1,才能定位到正确的原数据位置:
      plot(time_a(dec_max_idx), acceleration(star_row + dec_max_idx - 1,2), '^r','MarkerSize',10);
      plot(time_a(dec_min_idx), acceleration(star_row + dec_min_idx - 1,2), '^r','MarkerSize',10);
      
    3. 修正坐标轴范围逻辑:原axis语句的x轴用原数据行号,与time_a的秒数单位矛盾,改为基于time_a的实际范围:
      axis([min(time_a) max(time_a) 0 150]);
      
  • 额外优化建议:

    • 修正变量名拼写错误:time_satr应为time_start,避免后续代码混淆。
    • 简化极值计算:(acceleration(star_row:end_row,2).^2).^0.5等价于abs(acceleration(star_row:end_row,2)),可提升代码可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 22:15:27