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

1 vue (au cours des 30 derniers jours)
Mikhail le 3 Avr 2024
Commenté : Mikhail le 6 Avr 2024
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 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Mathieu NOE le 3 Avr 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
b = 1x4
20 12 8 8
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Mikhail le 6 Avr 2024
Thank you

Connectez-vous pour commenter.

### Plus de réponses (1)

Torsten le 3 Avr 2024
Modifié(e) : Torsten le 3 Avr 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)
b = a(1,1)
- I don't know.
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Mikhail le 6 Avr 2024
It does not work.

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by