I am having the error of array indices must be positive in this code.
Show older comments
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
William
on 6 Apr 2021
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");
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)
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.
Categories
Find more on Subplots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!