MATLAB Answers

0

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

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 件のコメント

Stephen Cobeldick
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:

サインイン to comment.

1 件の回答

回答者: Adam Danz
2019 年 5 月 6 日
編集済み: Adam Danz
2019 年 5 月 7 日

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}

  0 件のコメント

サインイン to comment.



Translated by