필터 지우기
필터 지우기

Is it possible to assign variables in the workspace to other variables using for loop?

조회 수: 6 (최근 30일)
I have variables like a_1_1, a_1_2, a_1_3, a_2_1, a_2_2, etc...... in the workspace. I want to assign these variables to another variable inside a for loop. Such that for each loop each variable will be loaded. For instance,
for i=1:100
for j=1:3
e=a_i_j
end
end
The abovementioned is just a pseudo code only for understanding.
How this can be done inside a for loop?
  댓글 수: 1
Stephen23
Stephen23 2024년 5월 21일
편집: Stephen23 2024년 5월 22일
"I have variables like a_1_1, a_1_2, a_1_3, a_2_1, a_2_2, etc...... in the workspace"
Why?
Forcing meta-data into variable names makes accessing your data slow, inefficient, buggy, and complex:
So far you have not told us the most important information: how did you get all of those variables into the workspace? The place where those variables are loaded or imported into the workspace is the correct place to fix this bad data design. For example, by LOADing into an output variable:
S = load(..);

댓글을 달려면 로그인하십시오.

채택된 답변

Ayush Modi
Ayush Modi 2024년 5월 21일
편집: Ayush Modi 2024년 5월 21일
Hi Bipin,
Yes, it is possible. To dynamically access variables such as a_1_1, a_1_2, a_1_3, a_2_1, a_2_2, etc from the workspace within a loop, you can use the eval function.
Here is an example to demonstrate how you can achieve this:
for i = 1:100
for j = 1:3
varName = sprintf('a_%d_%d', i, j);
e = eval(varName);
...
end
end
Refer to the following MathWorks documentation for more information on "eval" function:
  댓글 수: 7
Stephen23
Stephen23 2024년 5월 23일
편집: Stephen23 2024년 5월 23일
"data was loaded using load function."
Do not LOAD directly into the workspace. Always LOAD into an output variable:
S = load(..);
S will be a scalar structure. You can access its fields using e.g.:
C = fieldnames(S);
S.(C{1}) % the first field
or generate the fieldnames using e.g. SPRINTF.
Much better: use actual indices rather than forcing pseudo-indices into variable names.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Steven Lord
Steven Lord 2024년 5월 21일
Can you dynamically create or work with variables with numbered names like a_1_1, a_1_2, a_1_3, a_2_1, a_2_2, etc.? Yes.
Should you do this? The general consensus is no. That Discussions post explains why this is generally discouraged and offers several alternative approaches.

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by