How can I get the variable from inside of the for loop and use it /display it after for loop?

8 ビュー (過去 30 日間)
Hi,
I created a for loop. Inside this for loop I calculated a variable. Unfortunately Matlab deletes the variable after the end of the for loop. How can I use the calculated variable outside of the for loop? Thanks!

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 10 月 26 日
編集済み: Azzi Abdelmalek 2012 年 10 月 26 日
That depends where your loop is, in script file or function file If it's in Function file, that have nothing to do with a loop , you declare your variable global, If it's in the script file, your variable can't be deleted. look at these examples
for k=1:10
x=sin(k)
end
the result is x=sin(10); the previous x where erased, if you want to save them
for k=1:10
x(k)=sin(k)
end
  3 件のコメント
Arthur
Arthur 2012 年 10 月 26 日
In a function it's better to return is as a variable. Easier and saver.
function x = myLoop()
for k=1:10
x(k)=sin(k)
end
Simon
Simon 2012 年 10 月 26 日
Ok, thanks. Now it works without globals!

サインインしてコメントする。

その他の回答 (1 件)

Sachin Ganjare
Sachin Ganjare 2012 年 10 月 26 日
Declare that variable as global, so that matlab won't delete it.
  4 件のコメント
José-Luis
José-Luis 2012 年 10 月 26 日
No it's not. It's a bad idea. Don't use globals. Have the function return the variable instead.
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 10 月 26 日
I don't agree with systematic, it's bad to use globals

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by