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

 Accepted Answer

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

More Answers (1)

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 Comments

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)
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

Sign in to comment.

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!