Why am I getting the error "Array indices must be positive integers or logical values"?

조회 수: 782 (최근 30일)
I want to compare the exponential of matrix "A" obtained by the summation formula and the one with the eigen values. However, I'm getting the following error when exponential is computed with the diagonalised form (E here). 
Array indices must be positive integers or logical values.
A = [1,2,1,3; 3,1,2,0; 2,2,1,4; 1,3,2,1]; [V,D] = eig(A); exp_A = 0; for k = 0:100 exp_A = exp_A + (A^k)/factorial(k); end disp(exp_A); 304.3054 340.7344 263.9243 320.0369 275.4796 308.2690 238.7711 289.0775 389.2552 436.7654 339.1998 410.7063 309.9581 347.7556 269.7020 326.5840 E = V*(exp(D))\V; disp(E); 0.0008 + 0.0000i -0.0001 - 0.0000i -0.0001 + 0.0000i -0.0007 - 0.0000i -0.0001 - 0.0000i -0.8364 - 0.1567i 0.1039 + 0.0000i 0.8393 + 0.1795i -0.0001 + 0.0000i 0.1039 + 0.0000i -0.8364 + 0.1567i 0.8393 - 0.1795i -0.0007 - 0.0000i 0.8393 + 0.1795i 0.8393 - 0.1795i -0.7766 - 0.0000i
  댓글 수: 5

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

채택된 답변

Kelly Kearney
Kelly Kearney 2024년 10월 21일
편집: MathWorks Support Team 2024년 10월 21일
MATLAB uses 1-based indexing, so the first element is accessed with index 1, not 0. This means array indices must be positive integers. For example, access the first element of a vector "A". 
A = [10, 9, 8, 7, 6]; Aval = A(1) % This returns 10. Meanwhile, A(0) returns an error.
MATLAB also accepts logical indexing, which can be useful when working with conditional statements. For example, say you want to know the values of "A" that is larger than 7. Use the > operator to return a logical array whose elements are logical 1 when an element in "A" is larger than 7; and logical 0 otherwise. 
ind = A > 7
Now that you know the locations of the elements meeting the condition, you can access the individual values that are larger than 7 by using "ind" as the index array. 
Avals = A(ind)
For more information, see Array Indexing
As others have mentioned, without providing the full code that caused the error, it is hard to pinpoint why this error occurs. For example, you can have a variable named "sum = 2" sitting in your workspace. So, when you try to call the built-in "sum" function to find the sum of array elements, such as "sum(0.1:0.1:1)", the existing variable is overshadowing it. The error occurs because MATLAB cannot extract the element with index 0.1, 0.2, and so on. To avoid this error, you should not use a variable name that conflicts with MATLAB built-in functions. 

추가 답변 (11개)

Roya Kakar
Roya Kakar 2022년 1월 19일
Please answer my quesion. I get the following error after running this line of code
sm =sum(table2array(X));
Array indices must be positive integers or logical values.

henry espinoza
henry espinoza 2020년 6월 19일
편집: Walter Roberson 2024년 11월 21일
Array indices must be positive integers or logical values.
Error in Tarea3_HE (line 15)
Xc1 = (-1 /(PRM(u)*(w)))*j
  댓글 수: 1
Walter Roberson
Walter Roberson 2024년 11월 21일
Your variable u contains zeros or negative values or fractions.
You might have thought that PRM is a function, but at that point in the code it is a variable.

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


laura celis
laura celis 2022년 3월 12일
편집: Walter Roberson 2024년 11월 21일
tengo este error
Array indices must be positive integers or logical values.
Error in recortedesenales (line 38)
z1= z(A:B);
  댓글 수: 1
Walter Roberson
Walter Roberson 2024년 11월 21일
Your variable A(1,1) is negative, or zero, or contains fractions, and B(1,1) is greater than A(1,1) .
B(1,1) is not necessarily an integer and is not necessarily an integer-value more than A(1,1). For example, 3:5.1 is a valid indexing vector because it expands to [3 4 5]

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


Roshan Siwakoti
Roshan Siwakoti 2022년 10월 21일
a(i) =((delta_p2)/(2*tau(j)*(t_traj(j+1)-t_traj(j))))-((delta_p1)/(2*tau(j)*(t_traj(j)-t_traj(j-1))))
Array indices must be positive integers or logical values
  댓글 수: 3
Kelly Kearney
Kelly Kearney 2022년 10월 21일
Possible guess... Is a(i) supposed to be a(j)? If you haven't otherwise set i to be an integer, it defaults to sqrt(-1), which cannot be used as an index. Same goes for j; check that it's an integer. Best practices in Matlab recommend avoiding i or j as indices for this very reason.
Walter Roberson
Walter Roberson 2022년 10월 21일
I predict that your j is 1 so j-1 is 0 which is not a valid index.

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


Ferlyn
Ferlyn 2022년 11월 14일
편집: Walter Roberson 2024년 11월 21일
% c. x(t) = 3*exp(-2*t)u(t)
subplot (4,2,3)
y = 3*exp(-2*t).*(u(t));
plot (t,y,'-g','Linewidth', 2);
axis ([-1 5 -1 5]);
grid on;
xlabel ('t in sec');
ylabel ('x(t)');
title ('plot of (c)');
Here's my code and it says "Array indices must be positive integers or logical values". What should I do to fix it? Thank you.
  댓글 수: 1
Walter Roberson
Walter Roberson 2024년 11월 21일
I predict that u is a vector and t is not positive integers.
It is common for u(t) to intend to refer to the unit step function applied to t -- but it is also common for u to be defined as a vector. For example you might have
u = t>=0;
and if you had that and then tried u(t) it would be an attempt to index the vector u at locations given by t, but t probably starts with 0.

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


Nerea Espinosa Giralt
Nerea Espinosa Giralt 2022년 11월 19일
Hola!
Tengo este error." Array indices must be positive integers or logical values."
Atenuacion=(k*R_001^alfa*u(p))*(R_001)^(0.38/Ls-0.25/(1+n(p/0.01)^(-0.36)*longitud^m)*Ls);
¿podriais ayudarme por favor?
Gracias,
Saludos
  댓글 수: 3
Image Analyst
Image Analyst 2022년 11월 19일
You have u(p) which is u(0.05). There is no 0.05'th element of a matrix. Only the 1st element, 2nd element, 3rd element, etc.
Steven Lord
Steven Lord 2022년 11월 19일
The section of code with n(p/0.01) also looks like it might be missing a multiplication operator. If it isn't and you intended p/0.01 to give you an integer value you can use as an index into n, you may encounter difficulties due to floating point arithmetic. Even if that expression did happen to give an integer value (or you called round to force it to give an integer value) as written unless that integer value is 1 you're asking for an element of n that doesn't exist.
x = 1;
y = x(2) % There is no second element
Index exceeds the number of array elements. Index must not exceed 1.

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


Fariha
Fariha 2023년 8월 12일
편집: Walter Roberson 2024년 11월 21일
Hello, my code:
yoy(j,1)=100*(log(Real_Price(ii,1))-log(Real_Price(ii-4,1)));
every time I run it says '
Array indices must be positive integers or logical values.
'
can you help me understand my problem?
  댓글 수: 1
DGM
DGM 2023년 8월 12일
MATLAB sees that you're trying to index into an array. Array indices must be real positive (nonzero) integers (or logicals). So:
Is the index jj a real, positive integer?
Is the index ii a real, positive integer?
Is ii>4 so that ii-4 is always positive?
Is log() still interpreted as a function, or have you created a variable with the same name?

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


Maximilian
Maximilian 2023년 8월 18일
Hello, why am I getting the "Array indices must be positive integers or logical values." error for the code below. I cleared the workspace so that shouldn't be a problem.
Vi = 0;
Vf = 1;
R = 1000;
C = 10 * 10^-6;
t = linspace(0,0.1,1001);
r = R*C;
V(t) = Vi + (Vf-Vi).*(1 - (2.72 .^(-t/r)));
Plot(t,V(t))
  댓글 수: 2
Stephen23
Stephen23 2023년 8월 19일
편집: Stephen23 2023년 8월 19일
You Index into V using t:
V(t) = ...
Are the values of t valid indices? (hint: no) Get rid of them:
Vi = 0;
Vf = 1;
R = 1000;
C = 10 * 10^-6;
t = linspace(0,0.1,1001);
r = R*C;
V = Vi + (Vf-Vi).*(1 - (2.72 .^(-t/r)));
plot(t,V)
Walter Roberson
Walter Roberson 2023년 8월 19일
It is common to get confused between a formula and an array
A line such as
V(t) = Vi + (Vf-Vi).*(1 - (2.72 .^(-t/r)));
is typically intended to be a formula -- the left and right t are intended to refer to values
MATLAB does support creating formulas with that syntax, but only using the Symbolic Toolbox, such as
syms t
V(t) = Vi + (Vf-Vi).*(1 - (2.72 .^(-t/r)));
MATLAB would then refer to V as a "symbolic function".
MATLAB main support for creating formulas is for numeric formulas (that do not typically involve the Symbolic Toolbox). Those use a different syntax called "anonymous functions" that would look like
V = @(t) Vi + (Vf-Vi).*(1 - (2.72 .^(-t/r)));
In both the case of the "symbolic function" and this "anonymous function", V would become an object describing calculations that would be done if you pass values to the object, such as
V(3.2)
In both the symbolic function and the anonymous function, the t would refer to some indefinite value of t to be given value later, and the symbolic or anonymous function describes how to calculate the output in that future time when you finally get passed a specific value in place of t
But if you are not working with symbolic functions or anonymous functions (or some Object Oriented classes) then () is either for passing parameters to a function, or else for indexing. In the original code
t = linspace(0,0.1,1001);
V(t) = Vi + (Vf-Vi).*(1 - (2.72 .^(-t/r)));
you are working with definite numeric values for t not with a symbolic variable, so the right hand side is calculating definite numeric values, and the left side V(t) would be considered indexing.
Almost any time you have definite numeric values for t, V(t) on the left side of an assignment would be interpreted as an attempt to index. (There are some potential exceptions for Object Oriented classes.)

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


Lokesh
Lokesh 2024년 6월 4일
편집: Walter Roberson 2024년 11월 21일
Array indices must be positive integers or logical values.
Error in p3 (line 38)
f_triple_prime(i) = (f(i+1) - 3*f(i) + 3*f(i-1) - f(i-2)) / (deta^3);
  댓글 수: 2
DGM
DGM 2024년 6월 4일
편집: DGM 2024년 6월 4일
Well, considering that you're the only one that knows what your code does, did you try reading the error and then lookign to see if the given indices are positive integers?

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


Elián
Elián 2024년 11월 21일
편집: Walter Roberson 2024년 11월 21일
clear,
close all;
A=[1,9,1];
B=[2,4,7];
C=[10,-1,5];
paso=1;
retardo=0.01;
cont=1;
t=0:0.1:1;
x1=t*B(1)+(1-t)*A(1);
y1=t*B(2)+(1-t)*A(2);
z1=t*B(3)+(1-t)*A(3);
plot3(x1(1),y1(1),z1(1),'*r')
xlabel('eje x')
ylabel('eje y')
zlabel('eje z')
axis([-5 5 -5 5 -20 20])
title ('Trayectoria de una particula en el espacio (Grafica Elian Sayas)')
hold on
grid on
H=scatter3(x1(1),y1(1),z1(1),200, 'MarkerEdgeColor', 'k', 'LineWidth' ,3);
tiempo=['t=' ,num2str(t(1)), 's'];
Ht=text (A(1)+1, A(2)+1, A(3)+1, tiempo, 'Color', 'b', 'FontSize', 12);
for i= 2:paso:length(t)
delete(H),
delete(Ht),
T=plot3([x1 (i-1) x1(1)], [y1(1-1) y1(i)], [z1(i-1) z1(i)], 'b', 'LineWidth',1.2);
H=scatter3(x1(1) ,y1(i),z1(i),200, 'MarkerEdgeColor' , 'k', 'LineWidth',3);
tiempo=['t=',num2str(t(i)),'s'];
Ht=text(A(1)+1,A(1)+1,A(1)+1, tiempo, 'Color', 'b', 'FontSize',12);
F(cont)=getframe(gcf);
cont=cont+1;
pause(retardo)
end
hold on
t2=1:0.1:2;
x2=(2-t2) *B(1)+(t2-1) *C(1) ; y2=(2-t2) *B(2)+(t2-1) *C(2);
z2= (2-t2) *B(3)+(t2-1)*C(3) ;
plot3(x2(1), y2(1), z2(1), '*y')
for i= 2: paso: length(t2)
delete (H) , delete(Ht) ,
T=plot3([x2(i-1) x2(i)],[y2(i-1) y2(1)],[z2(1-1) z2(i)],'b' ,'LineWidth',1.
Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched delimiters.
H=scatter3(x2(i),y2(i),z2(i),200,'MarkerEdgeColor','k','LineWidth' ,3);
tiempo=['t2=',num2str(t2(i)),'s'];
Ht=text(A(1)+1,A(1)+1,A(1)+1,tiempo,'Color','b','FontSize',12);
F(cont)=getframe(gcf) ; cont=cont+1;
pause(retardo)
end
hold on
t3=2:0.1:20;
x3=cos(t3-2)-1+C(1);
y3=sin(t3-2)+C(2);
z3=t3-2+C(3);
plot3(x3(1),y3(1),z3(1),'*m');
for i= 2: paso: length(t3)
delete(H),
delete(Ht),
T=plot3([x3(i-1) x3(1)],[y3(1-1) y3(1)],[z3(i-1) z3(1)],'b', 'LineWidth',1.2);
end
video-Videowriter('ANIMACION_TRAYECTORIA', 'Uncompressed AVI');
open(video)
writeVideo(video,F)
close(video)
  댓글 수: 1
Walter Roberson
Walter Roberson 2024년 11월 21일
Your line
T=plot3([x2(i-1) x2(i)],[y2(i-1) y2(1)],[z2(1-1) z2(i)],'b' ,'LineWidth',1.
is missing a ")" at least. it was probably intended to be
T=plot3([x2(i-1) x2(i)],[y2(i-1) y2(1)],[z2(1-1) z2(i)],'b' ,'LineWidth',1.2);

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


Astrid
Astrid 2025년 4월 3일
편집: Walter Roberson 2025년 4월 3일
%apartir de codiciones actualizar los valores
h2b=zeros(1,length(nh));
for i=1:length(nh)
if i==3 % cuando n=0
h2b = 0.9975;
elseif i==4% cuando n=1
h2b(i)=-0.9975+0.995.*h2b(i-1);
elseif i<4
h2b(i)=0.995.*h2b(i-1);
end
end
  댓글 수: 1
Walter Roberson
Walter Roberson 2025년 4월 3일
Consider the case of i=1 then i==3 is false and i==4 is false, but i<4 is true. So the line
h2b(i)=0.995.*h2b(i-1);
is to be executed. But when i=1 then that would be
h2b(1)=0.995.*h2b(1-1);
which would be
h2b(1)=0.995.*h2b(0);
which is a problem because indices must be positive integers and cannot be 0.
Notice by the way that the for loop has no work to do if i is greater than 4. In such a case you might as well code it without a loop, such as
L = length(nh);
if L >= 1
h2b(1) = something;
end
if L >= 2
h2b(2)=0.995.*h2b(1);
end
if L >= 3
h2b(3) = 0.9975;
end
if L >= 4
h2b(4)=-0.9975+0.995.*h2b(3);
end
This can potentially be reduced a fair bit if it is certain that nh will be at least a certain number of elements. For example if it is certain that length(nh) will be at least 4 then the code reduces to
h2b(1) = something;
h2b(2)=0.995.*h2b(1);
h2b(3) = 0.9975;
h2b(4)=-0.9975+0.995.*h2b(3);

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by