Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

See the code

x(1) = 0;
k = 1;
   while x(k) <=6

   x(k) = x(k) +2

    k = k +1;

end

So I want the code to output

x(1) = 2

x(2) = 4

x(3) = 6

Basically I want to write out a list of x(i)s, that gets updated during each iteration. But I am getting an "out of bound" error and I realize that there is a conflict with the way MatLab sees "()" as a vector.

Anyway to get around this?

EDIT1

What if I want to do

x = 0;
y = 0;
k = 1;
   while x <=6 && y<=13

   x = x +2;
   y = y + 3 +x;

    k = k +1;

end

I want this to output

x = 2

y = 5

x = 4

y = 8

But it's not doing that, and I don't want to do this in two separate scripts. I want to handle everything at once.

share|improve this question
    
Print Step #$k$ and then $x = ?$. –  John Habert Feb 7 at 7:02
    
@JohnHabert, wait what? –  sidht Feb 7 at 7:06
    
Skip trying to label your variable recursively. Just print the step number and the answer for that step. You are already counting what step you are at with $k$. –  John Habert Feb 7 at 7:07
    
You mean just have $x(k) + 2$ instead of $x(k) = x(k) +2$? I still get errors –  sidht Feb 7 at 7:10
    
I'm saying just do $x = x+2$; and for output generate something that looks like: Step #1 : x = 2, Step #2 : x = 4, etc. –  John Habert Feb 7 at 7:12

1 Answer 1

up vote 0 down vote accepted

There's an error in your code, in the line

x(k)=x(k) + 2

because x(k) is not yet defined. See the correct code:

x(1) = 0;
k = 1;
   while x(k) <=6

   x(k+1) = x(k) +2

    k = k +1;

end
share|improve this answer
    
What if I want to update two variables at once? –  sidht Feb 7 at 8:13
    
Provide an example. –  5xum Feb 7 at 8:13
    
See edit post please –  sidht Feb 7 at 8:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.