Alexander Drake
Alexander Drake

Reputation: 13

MATLAB While loop syntax

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?

Upvotes: 0

Views: 271

Answers (1)

KKS
KKS

Reputation: 1389

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.

Upvotes: 1

Related Questions