Matlab Error "Attempted to access -- ; index out of bounds because numel--=???.

12 ビュー (過去 30 日間)
Phoebe
Phoebe 2014 年 2 月 27 日
回答済み: Shuba Nandini 2024 年 11 月 12 日 5:49
If my code looks like the following;
time=0; %Initialise time
particleno=9
dt=0.01;
tfinal=40;
diagstep=10;
diagcounter=0;
while time<tfinal
tie=time+dt;
if ((int8(time/diagstep) * diagstep) == int8(time))
[xcounter] = ParticleCounterFun(x0, particleno);
diagcounter=diagcounter+1;
end
Xtcounter(diagcounter)=xcounter(diagcounter);
end %End while time<tfinal LOOP
the FUNCTION FILE FOR PARTICLECOUNTERFUN IS;
function [ xcounter ] = ParticleCounterFun( x0, particleno )
%Initialise counters used in E field diagnostics
counter01=0;
counter12=0;
counter23=0;
counter34=0;
counter45=0;
for np=1:particleno
if (0<=x0(np) & x0(np)<1)
counter01=counter01+1;
end
if (1<=x0(np) & x0(np)<2)
counter12=counter12+1;
end
if (2<=x0(np) & x0(np)<3)
counter23=counter23+1;
end
if (3<=x0(np) & x0(np)<4)
counter34=counter34+1;
end
if (4<=x0(np) & x0(np)<5)
counter45=counter45+1;
end
end
xcounter=[counter01 counter12 counter23 counter34 counter45];
end
Anyway i get this;
>> ParticlePusher Attempted to access xcounter(6); index out of bounds because numel(xcounter)=5.
Error in ParticlePusher (line 101) Xtcounter(diagcounter)=xcounter(diagcounter);
Help please!

回答 (1 件)

Shuba Nandini
Shuba Nandini 2024 年 11 月 12 日 5:49
Hi Phoebe,
The indexing error occurred because the 'Xtcounter' object is trying to access an element of 'xcounter' that does not exist. The xcounter variable depends on the value of the 'diagcounter' variable, which may have caused the error.
To resolve the indexing error in the code, kindly modify your code as shown below:
% Initialize array to store xcounter values at each diagnostic step
Xtcounter = [];
while time < tfinal
time = time + dt; % Update time in each loop
if ((int8(time / diagstep) * diagstep) == int8(time))
xcounter = ParticleCounterFun(x0, particleno);
% Increment diagnostic counter and store xcounter in Xtcounter
diagcounter = diagcounter + 1;
Xtcounter(diagcounter, :) = xcounter;
end
end
I have modified the code to ensure that each xcounter array is stored as a row in Xtcounter for every diagnostic step, rather than attempting to access individual elements.
I hope the above provided code will help you to resolve the issue!

カテゴリ

Help Center および File ExchangeColormaps についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by