필터 지우기
필터 지우기

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

조회 수: 2 (최근 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
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 CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by