Input variable name in a for loop

3 ビュー (過去 30 日間)
Karim ElShorbagi
Karim ElShorbagi 2020 年 11 月 25 日
回答済み: Ameer Hamza 2020 年 11 月 25 日
Let's say I have variables named w1, w2, w3, w4... from w1 up to w10
How do I plot them all seperately using a for loop? Something that works similar to:
for z=1:10
figure
plot(w[insert number here])
end
  2 件のコメント
Stephen23
Stephen23 2020 年 11 月 25 日
Numbering variables like that is a sign that you are doing something wrong.
Trying to access those variables will force you into writing slow, complex, inefficient code that is liable to bugs and is difficult to debug. Read this to know why:
The much simpler and much more efficient approach is to use indexing into one array (which could be numeric, cell, structure, table, etc). You should use indexing, just as the MATLAB documentation recommends.
Karim ElShorbagi
Karim ElShorbagi 2020 年 11 月 25 日
Oh, alright thanks I'll look into that

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

回答 (1 件)

Ameer Hamza
Ameer Hamza 2020 年 11 月 25 日
Stephen already suggested the correct way. For your current code, a quick fix is to define a cell array
C = {w1, w2, w3, w4, w5, w6, w7, w8, w9, 10}
for z=1:10
figure
plot(C{z})
end

カテゴリ

Help Center および File ExchangeAnnotations についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by