How can I fix "Index in position 2 exceeds array bounds" in for loop?

1 次查看(过去 30 天)
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

采纳的回答

Mathieu NOE
Mathieu NOE 2024-4-3
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
b = 1x4
20 12 8 8
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

更多回答(1 个)

Torsten
Torsten 2024-4-3
编辑:Torsten 2024-4-3
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by