2
a=1:5
for k=a
    if k<3
        a=[a k+5];
    end
disp(k)
end

When I run this code, I get these results:

1
2
3
4
5

k uses only the initial vector when it enters to the loop. I want it to update the values of a and take the new values of a too. Thus, my question is how do I get this result:

1
2
3
4
5
6
7
1
  • 3
    you can try: for k=1:length(a) Commented Dec 8, 2014 at 22:56

2 Answers 2

2
ints = 1:5;

i = 0;

while i ~= length(ints)   

   i = i + 1;

   if (i < 3)
      ints = [ints i + 5]
   end

   disp(i)

end
Sign up to request clarification or add additional context in comments.

1 Comment

@glglgl just forgot to increment i
1
a=1:5
i=1
while i<=length(a)
    k=a(i);
    if k<3
        a=[a k+5];
    end
    disp(k)
    i = i + 1
end

should do the trick. (Disclaimer: I didn't test it)

The index i iterates over a until it is really over.

3 Comments

When I test you code it enters an infinite loop with k = 1
thanks for help! and we should put an i=i+1; to the bottom of disp(k) to make it avoid infinite loop
@BarsGunduz and Benoit_11 Of course! Just added it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.