MATLAB: I keep getting an error for line 7 “subscript indices must either be real positive integers or logicals”. How to fix this code

subscript indices

a1 = 0.5;
b1 = 1;
c1 = 4;
t=0:20;
f(1)=1;
for t = 0:20;
f(t) = a1*cos(t) + b1*cos(4*t + pi/2) + c1*cos(8*t)+ pi/2;
end
plot (t,f)
xlabel('t (sec)');
ylabel('f(t)');

Best Answer

MAtlab doesn't accept negatives and zero as indices. Check your loop...
for t = 0:20
f(t) = a1*cos(t) + b1*cos(4*t + pi/2) + c1*cos(8*t)+ pi/2;
end
In the above the index of f is zero. So error popped out. Start the loop from 1. Also initialize the value of f to zeros.
a1 = 0.5;
b1 = 1;
c1 = 4;
t=1:20;
f = zeros(size(t)) ;
for i = 1:length(t)
f(i) = a1*cos(t(i)) + b1*cos(4*t(i) + pi/2) + c1*cos(8*t(i))+ pi/2;
end
plot (t,f)
xlabel('t (sec)');
ylabel('f(t)');
%%no loop
f = a1*cos(t) + b1*cos(4*t + pi/2) + c1*cos(8*t)+ pi/2;