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

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 Comment

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");

Sign in to comment.

Answers (1)

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.

Asked:

on 6 Apr 2021

Commented:

on 6 Apr 2021

Community Treasure Hunt

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

Start Hunting!