0

I'm using the code

 k = 0;
 while k<3
 k = k+1;
 a = 5^k;
 disp(a);
 end

however, when the result outputs it only gives me the answer of one iteration. I'm wondering what the difference is to the computer when you use this code instead:

 clear, clc
 k = 0;
 while k<3
 k = k+1;
 a(k) = 5^k;
 end
 disp(a)

Why does the first code sample output only 125, while the second one outputs 5, 25, and 125?

5
  • are you sure that the first code result is 125 ? Commented May 16, 2016 at 2:28
  • I get [5;25; 125], and [5,25,125] for the two codes. Why are you doing while rather than for? Commented May 16, 2016 at 2:52
  • You may want to read the getting started document Commented May 16, 2016 at 6:41
  • I was using code that was displayed for an example in an engineering computing textbook. They used this example to demonstrate while loops. Commented May 19, 2016 at 14:22
  • And thanks. I'll check out that document!😊 Commented May 19, 2016 at 14:23

1 Answer 1

1

In the first code, variable a is scalar. So, Matlab erases and re-writes value into variable a in every iteration.

But, in case of second code, as you defined array index k at variable a, Matlab understands your variable a(k) as array variable. And, in every iteration, Matlab writes the assigned value 5^k on corresponding array point.

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

1 Comment

thanks, that's a great interpretation and explanation!

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.