Hello! I want to generate some dynamic variables using for loop. can anybody help?
1 次查看(过去 30 天)
显示 更早的评论
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
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
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}
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!