Change variable name based on what loop it is on

조회 수: 10 (최근 30일)
Annie
Annie 2025년 4월 14일
편집: Stephen23 2025년 4월 15일
I have a user input a vector for the variable titled 'k1'. A loop is set up where the input conditions are the same, but the variable name must be changed in order to perform some operations and store the data. I would like it to change based on which loop it is performing, like k1 might be given the name k2 on the second loop. I don't know how I could do this simply or if doing this is possible.
  댓글 수: 1
Stephen23
Stephen23 2025년 4월 14일
편집: Stephen23 2025년 4월 15일
"I don't know how I could do this simply or if doing this is possible."
It is possible, but is best avoided:
The neat, simple, robust, reliable, efficient alternative is to use indexing. You should use indexing.

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

채택된 답변

KALYAN ACHARJYA
KALYAN ACHARJYA 2025년 4월 14일
Optimized Memory Usage Strategy:
To efficiently utilize memory based on the type of output variable k, consider the following approach:
  1. If k is a scalar output (single numeric value per iteration):Preallocate a numeric array to improve performance and memory usage.
k = zeros(array_size1, array_size2); % Preallocate for scalar values
for i = 1:array_size
k(i) = ... ; % Assign scalar result
end
2. If k stores vectors or non-scalar data types (e.g., strings, structures, or arrays):
Use a cell array to accommodate varying data sizes/types.
k = cell(Cellarray_size1, Cellarray_size2); % Preallocate cell array
for i = 1:array_size
k{i} = ... ; % Assign vector or other complex result
end

추가 답변 (2개)

Walter Roberson
Walter Roberson 2025년 4월 14일
편집: Walter Roberson 2025년 4월 14일
It is possible to do this.
It is not possible to do this simply.
We firmly recommend that you do not do this.

dpb
dpb 2025년 4월 14일
While it can be done, it almost never should be the way..."there be dragons!" and slow, obfuscated and very difficult to debug code. See <Do not use globals or eval>. The direct link is to @Matt Fig's answer, but the overall discussion/thread is informative and valuable. The offcial Mathworks documentation link <Alternaives to the eval Function> discusses exactly the thing you mention as its first use case...

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by