for loop only gives me one value

hello, i'm trying to write this code, however when I calculate xi it keep giving me one value, even though both alpha_g and ki_1 has 6 values. which then stops me from calculating yi with the following error
Index exceeds the number of array elements (1).
Error in Module_b (line 44)
yi(i)=xi(i).*ki_1(i);
this is the code:
for i=1:nc
if (min<alpha_g(i)&&alpha_g(i)<max)
for i=1:nc
xi(i)= z1./(1+alpha_g(i).*(ki_1(i)-1));
for i=1:nc
yi(i)=xi(i).*ki_1(i);
end
end
elseif alpha_g>=1
yi=z1;
else
xi=z1;
end
end

 Respuesta aceptada

David Hill
David Hill el 16 de Feb. de 2022
Only one loop is needed.
for m=1:nc %don't use the same indexing variable (you are already inside a loop)
xi(m)= z1./(1+alpha_g(m).*(ki_1(m)-1));
yi(m)=xi(m).*ki_1(m);
end

Más respuestas (1)

Torsten
Torsten el 16 de Feb. de 2022
You only set xi(1) in
for i=1:nc
xi(i)= z1./(1+alpha_g(i).*(ki_1(i)-1));
but refer to xi(1) up to xi(6) in the following loop
for i=1:nc
yi(i)=xi(i).*ki_1(i);
end
Furthermore, since there are nested loops in your code fragment, you cannot use the same loop index "i" every time.

2 comentarios

Eyad Alkhotani
Eyad Alkhotani el 16 de Feb. de 2022
I didn't understant, I thought by referring i to be from 1 to nc that means that I'm referring for xi from 1 to nc(6)
Torsten
Torsten el 16 de Feb. de 2022
For this, you have to close the first for-loop:
for i=1:nc
xi(i)= z1./(1+alpha_g(i).*(ki_1(i)-1));
end
for i=1:nc
yi(i)=xi(i).*ki_1(i);
end
or simply
for i=1:nc
xi(i)= z1./(1+alpha_g(i).*(ki_1(i)-1));
yi(i)= xi(i).*ki_1(i);
end

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 16 de Feb. de 2022

Comentada:

el 16 de Feb. de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by