简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM