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

Matlab‘位置1索引超出数组边界’错误排查及代码调试请求

解决Matlab中「位置1的索引超出数组边界」错误

问题根源

你代码里的核心错误是:在把all_init_conditions转置赋值给iCon后,又执行了iCon=[];将这个数组清空。循环里访问iCon(i,3)时,iCon是空数组,直接触发索引越界错误。

此外还有几个次要问题会导致后续运行异常:

  • ode45的返回值覆盖了全局的iCon,会把初始条件数组冲掉
  • 最后查找最高分位置的代码语法错误,MaxScore未定义且赋值方式不对
  • 循环内的height更新逻辑和初始条件的列对应关系有偏差(你注释里标注h0是第三列,但代码里取了vary的第四列)

修复步骤

  1. 删除清空iCon的代码:删掉%Optimality score下方的iCon=[];行,保留之前的iCon(:,:) = all_init_conditions(:,:)';
  2. 避免覆盖初始条件数组:把ode45返回的状态数组换个变量名(比如currentCon),不要用iCon
  3. 修正height的列索引:根据注释的初始条件定义(第三列是altitude),循环内的height应该取currentCon(end,3),而非vary(end,4)
  4. 修正最高分查找逻辑:先定义MaxScore为找到的最大值,再用正确语法获取索引

修正后的完整代码

load 'all_init_conditions.mat'

%% initial conditions
linit= length(all_init_conditions(1,:));
iCon(:,:) = all_init_conditions(:,:)';
%v0 velocity
%T0 Flight Path Angle
%h0 altitude
%x0 horizontal distance
%m0 mass
gMoon = 1.6;
isp = 255;

%Optimality score
EndTime=[];
AltitudeScore = [];
%(1-hf)*100;
VelocityScore =  [];
%(1-(vf/2))*200;
GammaScore = [];
%(1-((pi/2)+Tf))*200;
TotalScore = [];

t = 0; 

Mathf = struct(); 

%calling EOM as dydt
dydt=@(t,iCon)GravityTurnEOM(t,iCon,gMoon,isp);
%% conditions

%% code part 1
%tstep
options = odeset('RelTol',1e-10);

for i=1:linit

    height = iCon(i,3);

    dt=0.2;
    vary = []; % 初始化vary避免未定义报错

while height > 0.1
   tstep=0:0.2:dt;

    [t,currentCon]=ode45(dydt,tstep,iCon(i,:),options);

    vary=[t,currentCon];

    dt=dt+0.2;

    height=currentCon(end,3); % 对应初始条件的第三列(h0)
end
Tend = vary(end,1);
Vfinal = vary(end,2);
Gfinal = vary(end,3);
AltFinal = vary(end,4); 

EndTime(i) = Tend;

Mathf(i).output = vary;

%Calculate all different scores including TotalScore
VelocityScore(i) = (1-(Vfinal/2))*200;
GammaScore(i) = (1-((pi/2)+Gfinal))*200;
AltitudeScore(i) = (1-AltFinal)*100;

TotalScore(i) = AltitudeScore(i) + GammaScore(i) + VelocityScore(i); 

if Gfinal < (-95*(pi/180))||Gfinal > (-85*(pi/180))||Vfinal>1% convert to radians

AltitudeScore(i) = 0;
GammaScore(i) =0;
VelocityScore(i) =0;
TotalScore(i)=0;

end

end

% Looking for max value in TotalScore vector.
MaxScore = max(TotalScore(:));
%Find the position in TotalScore in which Max Score exists
r = find(TotalScore == MaxScore, 1); % 只取第一个最大值的索引

BestStates = Mathf(r).output(:,2:6);

writematrix(BestStates,'MatrixBestStates.csv');

内容的提问来源于stack exchange,提问作者Olivia Scarry

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:37:53