【问题标题】:decoding array inputs and while loops解码数组输入和while循环
【发布时间】:2020-01-25 04:37:04
【问题描述】:

我基本上只需要帮助在matlab中解码这段代码,每一行是什么意思,它有什么作用?

基本上,创建一个数组 g,其中 g 中的每个值都是 g 的前一个值,但是是平方的。当 g 达到或大于 g 原始值的 100 倍时停止。

g = input('Please provide an initial value: '); 

while ((g == 1) || (g == 0))    
           disp('Cannot be 0 or 1')    
           g = input('Please provide an initial value: ');
end

i = 1; 
while ((g(i)^2)<=(100*g(1)))    
        g(i+1) = g(i)^2;    
        i = i+1; 
end

g = g'

代码要求输入一个不能为 0 或 1 的数字。然后该数字被平方,但在下一个值小于或等于初始数字的 100 倍时停止。

例如,如果您输入 2 代码会吐出 2, 4, 16,然后停止,因为下一个值是 256,大于 2 * 100 = 200。

提前谢谢你。

【问题讨论】:

  • 你问代码做什么,然后解释代码做什么。我不明白你在这里问什么。您可以在 MATLAB 中输入 help xxx 以获取有关 xxx 的帮助。对您不理解的代码中的每个单词执行此操作并立即执行!
  • 我建议不要在这里问这样的问题,而是在调试器中单步调试代码(只需单击第一行代码的左边距,创建一个断点,然后运行代码)。您将看到每一行的作用以及它如何更改所涉及的变量。您还可以在 MATLAB 命令提示符中键入部分表达式以查看它们的作用。自己探索东西,不要依赖别人向你解释。这样你会学到更多。如果有一个陈述真的难倒你,请在此处询问有关该陈述的问题。

标签: arrays matlab loops conditional-statements


【解决方案1】:
g = input('Please provide an initial value: '); 
//print this out to screen ; wait for user to type in ; press enter ;
// g becomes the number that the user type in ;
while ((g == 1) || (g == 0))    
// while g equals to 1 or g equals to zero ;
    disp('Cannot be 0 or 1')    
//print this statement to screen / console ;
    g = input('Please provide an initial value: ');
//print this out to screen ; wait for user to type in ; press enter ;
// g becomes the number that the user type in ;
end
// end the while loop ;
i = 1; 
// let i be the counter / index ; only to control the looping ;
while ((g(i)^2)<=(100*g(1)))    
// while i-th element of g is less than or equal to 100 times first element of g ;
    g(i+1) = g(i)^2;    
// i+1-th element of g is define as i-th element of g squared ;
// note that g actually becomes an array when this statement runs ;
    i = i+1; 
// i is define as i plus 1 ; meaning if i was 1 i is now 2 ;
end
// end the while loop ;
g = g'
// g become g transpose ; Matlab default to row array so this make it column array ;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2020-10-28
    • 2015-10-21
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多