How can I fix "Index in position 2 exceeds array bounds" in for loop?
1 view (last 30 days)
Show older comments
p=1;c=[1 0 4 8];n=4;b=[];j=1;
b=a(1,1)
a=flip(c)
for i=n-1:-1:1
b(1,i)=b(1,i+1)*p+a(1,i);
end
b
0 Comments
Accepted Answer
Mathieu NOE
on 3 Apr 2024
hello
to make your code work, b should be initiallized with same dimensions as a (as a vector, not just one scalar)
also it's not clear when you write b=a(1,1) if you meant the first or last element (iteration) of vector b
p=1;
c=[1 0 4 8];
n=4;
j=1;
a=flip(c);
b=zeros(size(a));
b(1,4)=a(1,1);
for i=n-1:-1:1
b(1,i)=b(1,i+1)*p+a(1,i);
end
b
More Answers (1)
Torsten
on 3 Apr 2024
Edited: Torsten
on 3 Apr 2024
When you set
b = a(1,1)
, a is undefined in your code from above.
Further, b is a scalar value, namely b = a(1,1). When you enter the for-loop, you want to compute b(1,3) as
b(1,3) = b(1,4)*p+a(1,3)
. But b(1,4) does not exist.
Maybe you want to set
b(1,4) = a(1,1)
instead of
b = a(1,1)
- I don't know.
See Also
Categories
Find more on Loops and Conditional Statements 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!