Hello! I want to generate some dynamic variables using for loop. can anybody help?

1 回表示 (過去 30 日間)
Chirag Dudhat
Chirag Dudhat 2019 年 5 月 6 日
編集済み: Adam Danz 2019 年 5 月 6 日
I want to generate a dynamic variable Aij, where I could assign this variable A different suffix i and j using for loop. so i could get variables like :
A11(i=1,j=1)
A11 , A12 , A13 , A14 , A15....................................A1j (where i=1, j=1,2,3,4...........n)
A21 ,A22 , A23 , A24 , A25....................................A2j (where i=2, j=1,2,3,4...........n)
A31 , A32 , A33 , A34 , A35....................................A3j (where i=3, j=1,2,3,4...........n)
...
...
...
An1 , An2 , An3 , An4 , An5...................................Ann (where i=n, j=1,2,3,4...........n)
why i am interested in generating such variables? because i want to assign these variables values which depends on i and j. So the variable itself represnts its value. in other words i could just tell the values of i and j by just looking at the variable itself.
for example:
Aij=i+j
A23=2+3=5
so by just looking at A23 i could guess its value.
  1 件のコメント
Stephen23
Stephen23 2019 年 5 月 6 日
編集済み: Stephen23 2019 年 5 月 6 日
Accessing dynamic variable names is one way the beginners force themselves into writing slow, complex, obfuscated, buggy code that is hard to debug. Read this to know why:
Indexing is neat, simple, and very efficient, unlike what you are trying to do. You should use indexing:

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

回答 (1 件)

Adam Danz
Adam Danz 2019 年 5 月 6 日
編集済み: Adam Danz 2019 年 5 月 6 日
Don't use dynamic variable names. It looks like you would benefit from storing your data in a [n-by-m] cell array like this:
n = 5;
m = 10;
data = cell(n,m);
for i = 1:n
for j = 1:m
data{i,j} = myfunc(x,y);
end
end
Instead of having a variable named "A35" you can access the cell A{3,5}.
If all of your data are numeric scalars, you could use a matrix instead of a cell array.
data = nan(n,m);
for i = 1:n
for j = 1:m
data(i,j) = myfunc(x,y);
end
end
A(3,5) %instead of A{3,5}

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by