For loop with dynamic variable name condition

조회 수: 2 (최근 30일)
Ignacio Lobato
Ignacio Lobato 2015년 4월 27일
편집: Stephen23 2019년 6월 19일
Hi!
I am trying to go through a lot of variables in a for loop and I would like to find a way to do that. In GUI, you select with the CheckBox the variables you want to plot. The loop I am trying to do takes the chosen boxes and prints the image of them in their respective folders. The problem I have is that I cannot convert the string to a variable name and with an array it would not work, as I would have to convert all variable names to an array first.
Here the code:
Variable names: check0, check5, check10, check15,... check85, check90
for j=0:5:90
%Evaluate if it checked, the following does not work for me
currentKW=eval(genvarname(sprintf('check%d', j)));
if currentKW==1 %If it is true
print(figure1,'-dbmp',sprintf('Images/BMP/Intensity_at_%d_KW',j))
end
end
  댓글 수: 1
Guillaume
Guillaume 2015년 4월 27일
Times and times again, we keep saying in this forum DO NOT create variables with dynamic names. Every time you want to use the variables you have to recreate these names, leading to obscure code that mlint can't analyse and help you with, that is hard to debug, and that can't be optimised by the JIT compiler.
I would stop digging that hole you're in and review the design to use cell arrays, structures or maps to hold your data.
As for your code snippet, it works fine for me with some made up values, so you would have to explain better what does not work for me mean. If an error is emitted, post the full error message.

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

답변 (1개)

Stephen23
Stephen23 2016년 1월 12일
편집: Stephen23 2019년 6월 19일

카테고리

Help CenterFile Exchange에서 Debugging and Analysis에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by