I am having the error of array indices must be positive in this code.

조회 수: 1 (최근 30일)
Zainab Ali
Zainab Ali 2021년 4월 6일
댓글: William 2021년 4월 6일
clear sin
f=10;
t=linspace(1,3,30);
x(t)=sin(2*pi*f*(t));
plot(t,x(t),'r');
title("without time shift");
subplot(2,2,1)
x(t)=sin(2*pi*f*(t-0.25));
plot(t,x(t),'b')
title("time shift by 0.25s");
subplot(2,2,2)
x(t)=sin(2*pi*f*(t-0.5));
plot(t,x(t),'g')
title("time shift by 0.5s");
  댓글 수: 1
William
William 2021년 4월 6일
Hi Zainab,
This problem is occurring because you are using t as as subscript to the array x(), and t does not have integer values. One way to fix this would be to write:
t = linspace(1,3,30);
for j = 1:30
x(j)=sin(2*pi*f*t(j));
end
However, this happens automatically if you just write
t = linspace(1,3,30);
x = sin(2*pi*f*t);
After this statement, x is an array of length 30. Also in the plot commands, you can just use "t" and "x" to refer to the entire arrays of values, so that your program becomes
clear sin
f=10;
t=linspace(1,3,30);
x=sin(2*pi*f*t);
plot(t,x,'r');
title("without time shift");
subplot(1,2,1)
x=sin(2*pi*f*(t-0.25));
plot(t,x,'b')
title("time shift by 0.25s");
subplot(1,2,2)
x=sin(2*pi*f*(t-0.5));
plot(t,x,'g')
title("time shift by 0.5s");

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

답변 (1개)

Cris LaPierre
Cris LaPierre 2021년 4월 6일
At least one of your indices is not valid, meaning it is either a non-integer value, or <=0. Here, the issue is that your vector t contains non-integer values. For example, here I try to access element 1.5:
a=1:3;
a(1.5)
Array indices must be positive integers or logical values.
My suggestion is to not try to use indexing in your assignment to x.
x=sin(2*pi*f*t);
If you were trying to use x(t) as a variable name, take a look at what MATLAB allows for variable names.

카테고리

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