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

1 view (last 30 days)
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 Comment
Stephen23
Stephen23 on 6 May 2019
Edited: Stephen23 on 6 May 2019
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:

Sign in to comment.

Answers (1)

Adam Danz
Adam Danz on 6 May 2019
Edited: Adam Danz on 6 May 2019
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}

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!