필터 지우기
필터 지우기

Is there way to easily change the value of multiple values using a for loop?

조회 수: 5 (최근 30일)
Nick
Nick 2021년 11월 14일
답변: Sahil Jain 2021년 11월 17일
This is hard for me to explain, but I was wondering if there was a way to use a for loop to simlify this code. My problem is that I dont know how I could call the specific variable in the for loop that is needed to be changed.
My Code:
if isempty(k1_exact)
k1_exact = -1;
end
if isempty(k2_exact)
k2_exact = -2;
end
if isempty(k1_U)
k1_U = -3;
end
if isempty(k1_L)
k1_L = -4;
end
if isempty(k2_U)
k2_U = -5;
end
if isempty(k2_L)
k2_L = -6;
end

답변 (1개)

Sahil Jain
Sahil Jain 2021년 11월 17일
Hi Nick. You can try using the "eval" function for your purpose. The following code snippet demonstrates how you may go about it.
variables = ["k1_exact", "k2_exact", "k1_U", "k1_L", "k2_U", "k2_L"];
for i=1:length(variables)
eval(strcat(variables(i), "=-", num2str(i)))
end
k1_exact = -1
k2_exact = -2
k1_U = -3
k1_L = -4
k2_U = -5
k2_L = -6
For every variable, we first create a string of the assignment expression. We then pass this string to the "eval" function to execute the operation.

카테고리

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

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by