Why am I getting an Indexing error while using sum

Hi, I am trying to plot this equation in Matlab:
e_t refers to a vector of randomly generated values, by putting e_t, I am simply trying to pull out the vector with such index.
This is my code:
clear;
alpha = 0.5;
n = 100;
e=randn(n,1);
e(1) = 0;
t = 1:1:n;
syms k
f(k) = (alpha.^(k-1)).*(e(k));
Error using indexing
Invalid indexing or function definition. Indexing must follow MATLAB indexing. Function arguments must be symbolic variables, and function body must be sym expression.
err = zeros(n,1);
tot = zeros(n,1);
for i=1:1:n
err(i) = subs(f,k,1:i);
tot(i) = (alpha.^(i-1)) + sum(err(i));
end
plot(t,tot)
I am currently getting "Error using indexing". I am new to matlab and appreciate any help. Thank you

2 Comments

Using symbolic variables as indices is not allowed. You have used the symbolic variable k as an index to the array e, that's why you get the error.
You can do this without using symbolic variables. Using a function handle instead would be much more efficient.
Also, how are e_t and alpha related to/dependent on i?
I am not certain what you want to do, however the symsum function may be necessary to get where you want to go.
clear;
alpha = 0.5;
n = 100;
e=randn(n,1);
e(1) = 0;
% t = 1:1:n;
syms k t
sympref('AbbreviateOutput',false);
e = sym('e',[1 n]);
f(k) = alpha.^(t-1) + symsum(e*alpha^(t-1), t, 1, n)
f(k) = 
f = vpa(simplify(f, 500), 5)
f(k) = 
return % STOP HERE
err = zeros(n,1);
tot = zeros(n,1);
for i=1:1:n
err(i) = subs(f,k,1:i);
tot(i) = (alpha.^(i-1)) + sum(err(i));
end
plot(t,tot)
.

Sign in to comment.

Answers (1)

e=randn(n,1);
e(1) = 0;
e is a vector.
syms k
k is a symbolic variable
f(k) = (alpha.^(k-1)).*(e(k));
With e being a vector, e(k) is a request to index e at the location designated by symbolic variable k. However, symbolic variables can never be used as indices.
You should construct the definite vector
k = 1 : n;
f = (alpha.^(k-1)).*(e(k));
and then index it as needed.
Question:
t = 1:1:n;
what is that for? You never use it.

Products

Release

R2023a

Asked:

on 8 Sep 2023

Commented:

on 8 Sep 2023

Community Treasure Hunt

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

Start Hunting!