# Why do I get the error 'Subscript indices must either be real positive integers or logicals. ' ?

조회 수: 2,282(최근 30일)
MathWorks Support Team 2013년 5월 7일
편집: Alexandra Roxana 2021년 10월 9일
Why do I get the following error message:
ERROR: Subscript indices must either be real positive integers or logicals.

### 채택된 답변

MathWorks Support Team 2021년 2월 17일
편집: MathWorks Support Team 2021년 2월 17일
This error occurs when you attempt to index into an array using indices that are not positive integers or logical values. Here are some tips for common situations that cause this error message:
1) Double check that your indices are positive integers. Indices in MATLAB cannot be 0, and by default, start with 1.
2) If you are using logical indexing to index into an array, be sure that your index array is of type 'logical', and not a 'double' array of 1s and 0s. You can convert a 'double' array to a logical array before attempting to use logical indexing. For example:
A = [1 2 3 4; 5 6 7 8];
ind_double = [0 1 0 1; 0 1 0 1];
ind_logical = logical(ind_double);
A(ind_logical)
For an index array 'ind', you can check its data type using the 'whos' function:
whos ind
3) If you use floating-point arithmetic to compute an index array, then the array values may not be exact integers. The 'round' function is handy when you know you have an index value that is nearly the integer index that you want. For example,
A = [1 2 3 4; 5 6 7 8];
ind_float = 2.00001;
ind_int = round(ind_float);
A(ind_float)
Below is a way to check if an index array 'ind'' contains exact integer values. This command returns a 'logical' array, where 1 indicates the index value is an exact integer, and 0 indicates it is not.
ind == round(ind)
4) If you assign a variable to the same name as a built-in function in MATLAB, then you will overwrite that function and encounter the error when you attempt to call it. For example,
max = rand(5);
A = rand(5);
max(A)
In this event, rename your variable and clear the old one to proceed:
B = max;
clear max max(A)
For more information on indexing in MATLAB, see the following documentation page:
##### 댓글 수: 6표시숨기기 이전 댓글 수: 5
Walter Roberson 2018년 9월 25일
"Has this been changed in a recent update of Matlab? (I updated from 2013 to 2017). Before that I never had to convert from double to logical."
R2013a:
>> A=rand(1,3), A([1 0 0])
A =
0.8147 0.9058 0.1270
Subscript indices must either be real positive integers or logicals.
Same with R2010bSP1, which is the oldest MATLAB I happen to have installed at the moment.
If we examine the R14 documentation, https://www.mathworks.com/help/releases/R14/techdoc/matlab.html in the document for " Special Characters [ ] ( ) {} = ' . ... , ; : % ! @ " we see,
"The components of V must be integers to be used as subscripts. An error occurs if any such subscript is less than 1 or greater than the size of X."
This is not a new restriction, and No, there is no setting in MATLAB that could change this.

댓글을 달려면 로그인하십시오.

### 추가 답변(21개)

Antoine Pichot 2015년 11월 19일
Iaredi Sabinas's comment should be a valid answer.
It may happen when you have a variable named after an existing matlab function, like min or diff. Matlab thinks you are using the variable instead of the builtin function.
##### 댓글 수: 1표시숨기기 없음
Stephen 2015년 11월 19일
It is already part of the answer: "Another common cause is that a variable has overwritten a function name and is thus shadowing the function. For example:..." and it then proceeds to give an example of how this can happen.

댓글을 달려면 로그인하십시오.

Schrecklich Er 2017년 3월 18일
편집: Walter Roberson 2017년 4월 4일
I got this message while I was trying process a image using 'imread', i had the following structure:
for i = 1 : f
for j = 1 : c
B(i,j)=([A1(i,j)*A2(i,j)]);
B1(i,j)=(A2(i,j)/A1(i,j));
end
end
i got the same error message so until 30 minutes of research I just switch the letter 'i' for a 'k' and the error message disapeared, I think that the error was there because the letter 'i' is used for imaginary numbers.
just a little hint! Hope it is useful.
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

댓글을 달려면 로그인하십시오.

how about this. the word that have star...how can i declare..if i run this prgoram it get error..thnx a lot
for i=0:1: maxrow-1
for j=0:1: maxcol-1
% inv([i, j]) = 255 - image([i, j]);
for k = 0: 1
*sto([i, j, k]) = image([i, j]);*
end
end
end
##### 댓글 수: 1표시숨기기 없음
Walter Roberson 2016년 4월 22일
MATLAB indexing starts at 1, not at 0. You need to add 1 to all of your indices.
Also remember that sto([i, j, k]) is indexing sto at 3 locations, sto(i), sto(j), sto(k). It is not an index into a 3 dimensional array: that would be sto(i, j, k)

댓글을 달려면 로그인하십시오.

Pratyush Lohumi 2017년 3월 18일
편집: Walter Roberson 2017년 3월 18일
for n = 0:ns
s(n) = (ns-n)/ns; %slip
Tmech(n) = ph*V1eq^2*R2/((s(n)*omegas)*((R1eq + R2/s(n))^2+(X1+X2)^2)); %Electromechanical torque
end %End of slip loop
Error: Subscript indices must either be real positive integers or logicals. (Line 2)
Query: Couldn't seem to rectify the mistake?
If someone could provide a valid explanation or a corrected code for this loop, that would really help my project.
##### 댓글 수: 3표시숨기기 이전 댓글 수: 2
Imen BOUGRINE 2017년 4월 4일
for m = 1:num_pulse_int
%Update sensor and target positions
[sensorpos,sensorvel] = sensormotion(1/prf);
[tgtpos,tgtvel] = tgtmotion(1/prf);

댓글을 달려면 로그인하십시오.

편집: Walter Roberson 2017년 4월 26일
for j=1:n
y(j)= (T(j)-Ts)/(Tb-Ts);
h(j)=(1/427)*(-0.0717)*L*(Tb-Ts)*(y(j+1)-y(j-1)/2*deltas);
r(j)=(e*sigma*L^2*P*Ts^3)/(kAc)*(((T(j)/Ts)^3)+((T(j)/Ts)^2)+(T(j)/Ts)+1);
c(j)=1-(h(j)*deltas/2);
a(j)=-2+(r(j)*deltas^2);
b(j)=1+(h(j)*deltas/2);
end
##### 댓글 수: 3표시숨기기 이전 댓글 수: 2
Walter Roberson 2018년 9월 25일
Ram: you had a k-5 subscript with k starting at 1. You need to start k at 6 or more.

댓글을 달려면 로그인하십시오.

Wellington Pereira Guedes 2017년 10월 3일
Somenone can help me. I got this erro when using this code below:
W2=[];%will contain watermark signal extracted from the image
for t=1:wmsz
W2 = [W2(D_w(IND(t,1),IND(t,2))/D(IND(t,1),IND(t,2)))*10] %watermark extraction
end
##### 댓글 수: 1표시숨기기 없음
Walter Roberson 2017년 10월 4일
Let us match brackets. The number will be the count of open brackets "after" the character aligned with:
W2 = [W2(D_w(IND(t,1),IND(t,2))/D(IND(t,1),IND(t,2)))*10]
1 2 3 4 3 4 32 3 4 3 4 321 0
We see from this that W2 is being indexed by
D_w(IND(t,1),IND(t,2)) / D(IND(t,1),IND(t,2))
1 2 1 2 10 1 2 1 2 10
which contains a division. So for the index into W2 to be an integer, D_w(IND(t,1),IND(t,2)) would have to be an non-zero integer exact integer multiple of D(IND(t,1),IND(t,2)) . That condition is not impossible, but it is something I would tend to doubt.

댓글을 달려면 로그인하십시오.

Yago Veloso 2017년 10월 6일
편집: Walter Roberson 2017년 10월 6일
Hi everyone! I get the same error in my code, I'm trying to connect a function to my main code, where the function supply my code with all variables of my system equation solution.
Below is part of my main code where I found this error:
[Y1des]= ANN (Z1,e1,s1,D);
[ ac, ao, at_coluna, kp, r1, r2, L, vj, ro_ar, visc_ar, k_ar, RA, P, t_ar, Tar_e, T_ar_ext, Urel_e, Urel, Uabs_e, cps, ro_p_ap, hparede, cal_lat, cpar, cpl, cpv, ro_p, dp, Ubs, u, Rep1, Nu, hp1, St, Rep2, hw1, e, ae1, aet, X1, t_seg, X, ae, hp, hw, d_xp, tt,z]= variaveis (h, Y1des, hi, uar, t_min);
[G ,u, Pvse, Pve, UAEsat, UAE, He]= prop_ar (ro_ar,uar,ac, ao, at_coluna,t_ar, Tar_e, Urel_e, P);
[vl, mg, mss]= prop_leito (ro_p_ap,ro_p,ro_ar,ac,hi,vj);
%%%Initial condition
Tp(1)= 298.15;
Tar_s(1)= Tar_e - ((1-exp(-X(1)))*(Tar_e-Tp(1)));
tar_s(1) = Tar_s(1)-273.15;
Here is the error message
Subscript indices must either be real positive
integers or logicals.
Error in Dif_finitas_plus_ANN (line 44)
Tar_s(1)= Tar_e -
((1-exp(-X(1)))*(Tar_e-Tp(1)));
Thanks for the help !!
##### 댓글 수: 3표시숨기기 이전 댓글 수: 2
Yago Veloso 2017년 10월 6일
Walter Roberson, thanks for the help! That's what was causing the error.

댓글을 달려면 로그인하십시오.

MarkusP 2018년 2월 5일
편집: MarkusP 2018년 2월 5일
hello guys, maybe someone of you is able to help me...I tried to fix my problem with the solution above but it wasn`t possible.
I get the same error message if I`m runnung the following skript. The skript is for solving a problem with methods of characteristic.
l=1;
d=0.01;
rho=1000;
f=0.1;
a=1;
p0=2e3;
v0=(p0*2*d/(l*rho*f))^0.5;
n=101;
h=l/(n-1);
v(1:n)=v0;
p(1)=p0;
for i=2:n
p(i)=p(i-1)-f*rho*v0^2*h/(2*d);
end
dt=h/a;
tmax=3;
itmax=tmax/dt;
fhr=f*h/(2*a*d);
for it=1:itmax
t=it*dt;
for i=2:n-1
pa=p(i-1);
pb=p(i+1);
va=v(i-1);
vb=v(i+1);
pc(i)=a/2*((pa+pb)/a+rho*(va-vb)+fhr*(vb*abs(vb)-va*abs(va)));
vc(i)=0.5*((pa-pb)/(a*rho)+va+vb-fhr*(vb*abs(vb)+va*abs(va)));
end
pc(1)=p0;
vb=v(2);
pb=p(2);
vc(1)=vb+(pc(1)-pb)/(a*rho)-fhr*vb*abs(vb);
vc(n)=v0*valve(t);
va=v(n-1);
pa=p(n-1);
pc(n)=pa-rho*a(vc(n)-va)+f*h*rho/(2*d)*va*abs(va); %%error is in this line
vres(it,1:n)=vc(1:n);
pres(it,1:n)=pc(1:n);
p=pc;
v=vc;
end
My valve(t) function looks like this:
function vrel = valve(t)
if t<.1
vrel=1;
else
vrel=exp(-10*(t-.1));
end
Here is the error message:
Subscript indices must either be real positive integers or logicals.
Error in MOCwaterhammer (line 45)
pc(n)=pa-rho*a(vc(n)-va)+f*h*rho/(2*d)*va*abs(va);
Thanks for you help!
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

댓글을 달려면 로그인하십시오.

Torsten 2018년 2월 5일
편집: Torsten 2018년 2월 5일
You forgot a multiplication sign:
pc(n)=pa-rho*a->*<-here(vc(n)-va)+f*h*rho/(2*d)*va*abs(va);
Best wishes
Torsten.
##### 댓글 수: 1표시숨기기 없음
MarkusP 2018년 2월 5일
Oh the solution can be so simple...
Thank you so much!

댓글을 달려면 로그인하십시오.

Francisca Belart 2018년 8월 30일
just using round()solved it for me.Thanks sooo much!
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

댓글을 달려면 로그인하십시오.

Hamza saeed khan 2018년 12월 21일
I think it may help. I myself remove (t) from c(t) and m(t) as follows:
clc
close all
clear all
%let values we asigned as followed
A1=4
A2=2
f1=5
f2=6
t=0.1:0.001:1
c=20*A1*cos(2*pi)*f1
m=12*A2*cos(2*pi)*f2
y=c*m
plot(y,t,'r')
xlabel('c(t)')
ylabel('m(t)')
grid on
Best wishes Hamza Pakistani lol
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

댓글을 달려면 로그인하십시오.

Miguel Angel Guzman de la Cruz 2019년 10월 7일
¿How I put a range in for loop that starts in a negative number?
Something like that
for i=-10000:100:10000
delta_g(i,1)=((4*R1^3*sp*G)/3)*(z1/(i^2+z1^2)^(3/2));
end
Salu2
##### 댓글 수: 1표시숨기기 없음
Stephen 2019년 10월 8일
Loop over indices, rather than looping over data.

댓글을 달려면 로그인하십시오.

Jamal Nasir 2020년 3월 31일
this error when a negative number or real number used as indecies of matrix
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

댓글을 달려면 로그인하십시오.

Sofia Santos 2020년 5월 8일
Hello, I tried using round() and convert double to logical, bue when I type "whos maximum" or "whos minimum" nothing is show. I want to now the time in minimum and the time in maximum for calculate de rise time.
Can you look ate my code and see if you can help? Thank you very much!!
data_org = importdata(sinais,'\t',7); %text file with 7 columms
EDA=data_org.data;
EDA= EDA(:,6); %I just want the values in the 6th column
T=N/fs;
t = (1:N)/fs;
minimum= min(EDAuS_filter);
maximum= max(EDAuS_filter);
amp=maximo-minimo; %signal amplitude
tmin=t(minimo);
tmax=t(maximo);
rise_time= tmax-tmin;
##### 댓글 수: 4표시숨기기 이전 댓글 수: 3
Sofia Santos 2020년 5월 8일
I'm not executing this in the context of a function. The idea is to create a script that reads the six column of each text file and then filter that signal and get the amplitude and time rise. But I'm getting troubles to find the corresponding t.

댓글을 달려면 로그인하십시오.

Seahawks 2020년 5월 27일
편집: Walter Roberson 2020년 5월 27일
"Subscript indices must either be real positive integers or logicals."
Error in Chanprojectpart32 (line 36)
E(Zr)=mean(Zr);
=====================
for j=1:N-1
s1 = 0;
s2 = 0;
for k=1:No+1
Phi=(pi-(-pi))*rand-pi;%Phi-k
Fk = Fd.*(cos((2*pi*k)/M)); %Fk
Bk = pi/(No+1)*k; %k(pi/No+1)
..........
.........
y6 = cos(2*pi*Fd*t + Phi);
s1 = s1 + y1*y2;
s2 = s2 + y5*y2;
end
Zr = NN*s1 + MM*(y3*y6);
Zi = NN*s2 + MM*(y4*y6);
end
E(Zr)=mean(Zr);
E(Zi)=mean(Zi);
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Seahawks 2020년 5월 30일
Thanks

댓글을 달려면 로그인하십시오.

Viktoriia Buliuk 2020년 8월 3일
Hello! I try to perform the transforn of obtained data from .csv file. Could you, please, help me. I have the following errors:
Subscript indices must either be real positive integers or logicals.
Error in walvet>@(tau)hh(tau)*(2/(3^(1/2)*pi^(1/4))*exp(-((tau-ttt(j))/a(i))^2/2)*(1-((tau-ttt(j))/a(i))^2))
Error in integralCalc/iterateArrayValued (line 156)
fxj = FUN(t(1)).*w(1);
[q,errbnd] = iterateArrayValued(u,tinterval,pathlen);
Error in integralCalc (line 103)
Error in integral (line 88)
Q = integralCalc(fun,a,b,opstruct);
Error in walvet (line 26)
Q = integral(F,-Inf,Inf, 'ArrayValued', true);
And the code is follofing:
type wet.csv
Test = importdata('wet.csv');
t = Test(:, 1);
h = Test(:, 2);
tt = max(t);
tr = min(t);
ttt = tr:4.0003*10^-11:tt;
hh = interp1(t, h, ttt);
figure(2);
plot(t, h, 'ro');
hold on;
plot(ttt, hh, 'g');
a = 0.3*10^-10:10^-11:10^-9;
for i = 1:length(a)
for j = 1:length(ttt)
F = @(tau) hh(tau)*(2/(3^(1/2)*pi^(1/4))*exp(-((tau-ttt(j))/a(i))^2/2)*(1 - ((tau-ttt(j))/a(i))^2));
Q = integral(F,-Inf,Inf, 'ArrayValued', true);
K = (1/(a(i)^(1/2)))*Q;
S = real(K);
end
end
contour (ttt, hh, a, S, 500)
Thank you very much!!!
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Viktoriia Buliuk 2020년 8월 11일
Thanks a lot!
I defined hh = @(t_per) interp1(t, h, t_per)

댓글을 달려면 로그인하십시오.

Destaw Masresha 2020년 12월 13일
편집: Walter Roberson 2020년 12월 13일
A=sort(fc);
B=A((c*d-n+1):c*d); % selete the top n of the variance
Subscript indices must either be real positive integers or logicals
##### 댓글 수: 1표시숨기기 없음
Walter Roberson 2020년 12월 13일
What are c and d ? What is n ?
I speculate that you constructed c and d such that you expect c*d to always be an integer, but that it is not always exactly an integer. For example if c were 0.1:0.1:1 and d were 10, then you might expect that c*d is always an integer, but that would be false:
format long g
c = 0.1 : 0.1 : 1;
mat2str(c)
ans = '[0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1]'
d = 10;
mat2str(c * d)
ans = '[1 2 3 4 5 6 7 8 9 10]'
mat2str(c * d - (1:10))
ans = '[0 0 4.44089209850063e-16 0 0 0 0 0 0 0]'
c(3) - 0.3
ans =
5.55111512312578e-17
Lessons:
• 0.1 is not exactly representable in double precision
• multiplying a double precision number that is "mathematically" a fraction, by something that "mathematically" give you back an integer... doesn't always give you back an integer. 0.3 * 10 does not give 3
• numbers calculated by fractional increments on colon operators, such as the third value of 0.1:0.1:1, are not always exactly the same as the corresponding literal value you would expect. 0.1+0.1+0.1 does not give you the same value as you would get from writing 0.3

댓글을 달려면 로그인하십시오.

common fernando 2021년 4월 5일
편집: Walter Roberson 2021년 4월 5일
hello guys, maybe someone of you is able to help me...I tried to fix my problem with the solution above but it wasn`t possible.
Why do I get the following error message:
Subscript indices must either be real positive integers or logicals.
Error in threeDFT (line 33)
x=v((j-1:j+N0-2)*dt);
code:
fs=50*512;
dt =1/fs;
N0=fs/50
tmax=1;
j_max=tmax*fs;
for j=1:j_max+1
x=v((j-1:j+N0-2)*dt);
##### 댓글 수: 9표시숨기기 이전 댓글 수: 8
Walter Roberson 2021년 4월 7일
The code you posted before was three months ago; I would think that you have developed the code further since that time.

댓글을 달려면 로그인하십시오.

neelu pareek 2021년 7월 11일
please someone help as i am getting this error for the first time although calculating and using gamma function many times in my work.
t=[0:.5:1];
eta=0.8;gamma=.03;p=.9;pi=.4;mu=.75,sigma=.7
S= mu+(( ((1-p)*(pi)^(mu))-(.5*(mu)^2*(eta)^(mu))-(mu*(sigma)^(mu)) )* (t.^( mu)/ gamma(mu + 1)))
mu =
0.7500
sigma =
0.7000
Subscript indices must either be real positive integers or logicals.
##### 댓글 수: 1표시숨기기 없음
Walter Roberson 2021년 7월 11일
gamma=.03
gamma stops being a function and starts being a scalar. gamma(mu+1) would then be an attempt to index the scalar.

댓글을 달려면 로그인하십시오.

Alexandra Roxana 2021년 7월 18일
Hello, I'm trying to solve the heat equation in 2D using the finite difference method. I've also changed k=0 to k=1 and u(k+1) to u(k) but still no result. Are the initializations correct?
clc
clear all
alpha = 2;
L=50;
dx = 1;
dt = (dx^2)/(4*alpha);
gamma = (alpha^dt)/(dx^2);
itert = 1000;
u=zeros(itert,L,L);
uinit = 0;
utop=100;
uleft=0;
ubottom=0;
uright=0;
%Boundary conditions
u(:,L-1,:)=utop;
u(:,:,1)=uleft;
u(:,1,1)=ubottom;
u(:,:,L-1)=uright;
for k=0:itert-1
for i=1:L-1
for j=1:L-1
u(k+1,i,j) = gamma*(u(k,i+1,j) + u(k,i-1,j) + ...
u(k,i,j+1) + u(k,i,j-1) - 4*u(k,i,j)) + u(k,i,j);
end
end
end
display(u)
##### 댓글 수: 7표시숨기기 이전 댓글 수: 6
Alexandra Roxana 2021년 7월 18일
Thank you very much! Yes, it was *dt.

댓글을 달려면 로그인하십시오.

Alexandra Roxana 2021년 10월 9일
편집: Alexandra Roxana 2021년 10월 9일
Hello! I'm having a similar problem. I'm trying to compute the solution of heat equation in 2D using the finite element method in iterative steps. The issue is that at the next step I have to compute the right-hand member using the previous solution in the triangle coordinates and that means uold(0,0) because those are the first triangle coordinates. Here is the code.
uold=zeros(M,N);
uold=u1;
%computing u2,...,uN
for s=2:N1
L=zeros(N*M,1);
for t=1:(2*(M+1)*(N+1))
n1=Tr(t,1);
n2=Tr(t,2);
n3=Tr(t,3);
x1=Nod(n1,1);
y1=Nod(n1,2);
x2=Nod(n2,1);
y2=Nod(n2,2);
x3=Nod(n3,1);
y3=Nod(n3,2);
M1=[x1 y1 1; x2 y2 1; x3 y3 1];
de=det(M1);
ariat=abs(de)/2;
C=inv(M1); %barycentric coord. coeff. matrix
a1=C(1,1);
b1=C(2,1);
c1=C(3,1);
a2=C(1,2);
b2=C(2,2);
c2=C(2,3);
a3=C(1,3);
b3=C(2,3);
c3=C(3,3);
Le=zeros(1,3);
Le(1)=uold(x1,y1)*ariat/3+f(x1,y1,s,dt)*dt*ariat/3;
Le(2)=uold(x2,y2)*ariat/3+f(x2,y2,s,dt)*dt*ariat/3;
Le(3)=uold(x3,y3)*ariat/3+f(x3,y3,s,dt)*dt*ariat/3;
end

댓글을 달려면 로그인하십시오.

### 태그

아직 태그를 입력하지 않았습니다.

### Community Treasure Hunt

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

Start Hunting!