MATLAB Debugging a Plot of V vs. z2 for June 7

  • Thread starter Thread starter QM3BP
  • Start date Start date
  • Tags Tags
    Debugging Plot
AI Thread Summary
The code attempts to plot a variable V against z2 but encounters an "index out of bounds" error due to the variable counter exceeding the length of x. The error arises because the counter is not reset during the nested loops, causing it to exceed the number of elements in x after the first iteration. Additionally, the code's formatting needs improvement for better readability. To resolve the issue, the counter variable should be reset at the beginning of each outer loop iteration. Proper indentation and formatting will enhance code clarity and help identify similar issues in the future.
QM3BP
Messages
1
Reaction score
0
Code:

mu12=5;
mu123=20/21;
z1=1:15;
z2=-10:0.05:10;

counter=1;
index=1;
count=1;
indexer=1;
m=1;
n=1;

for l=1:1:15;

for p=1:1:401;
x=(sqrt(mu12)/10)*z1(n)+z2/(sqrt(mu123));
y=(-(sqrt(mu12)/10)*z1(n))+(z2/(sqrt(mu123)));

z=1:401;
z(indexer)=z1(n)/sqrt(mu12);
indexer=indexer+1; end;

n=n+1; end

for q=1:1:15;

V13=[];
for i=0:1:398; if abs(x(counter))<1 V13(counter,m)=-1; else V13(counter,m)=0; end; counter=counter+1; end;

V23=[];
for j=0:1:398; if abs(y(index))<1 V23(index,m)=-1; else V23(index,m)=0; end; index=index+1; end;

V12=[];
for k=0:1:398; if abs(z(count))<1 V12(count,m)=-1; else V12(count,m)=0; end; count=count+1; end;

V=[];
V(:,m)=V12(:,m)+V23(:,m)+V13(:,m);

m=m+1; end;

plot(z2,V(:,1))





Error Message:

? Attempted to access x(402); index out of bounds because numel(x)=401.

Error in ==> Vvsz2plot_june7_debug at 28
for i=0:1:398; if abs(x(counter))<1 V13(counter,m)=-1; else V13(counter,m)=0; end; counter=counter+1; end;
 
Physics news on Phys.org
Learn to indent and format your code! We have a [ code ] tag at this site, but it won't help with your code because your code is formatted flush left.The problem is that you are never resetting the variable counter. That variable exceeds 401 on the second pass through the for q=1:1:15; loop.
 

Similar threads

Replies
4
Views
3K
Replies
1
Views
2K
Replies
1
Views
3K
Replies
10
Views
2K
Replies
5
Views
2K
Replies
4
Views
2K
Replies
2
Views
2K
Back
Top