For loop with dynamic variable name condition

10 Ansichten (letzte 30 Tage)
Ignacio Lobato
Ignacio Lobato am 27 Apr. 2015
Bearbeitet: Stephen23 am 19 Jun. 2019
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 Kommentar
Guillaume
Guillaume am 27 Apr. 2015
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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Stephen23
Stephen23 am 12 Jan. 2016
Bearbeitet: Stephen23 am 19 Jun. 2019

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by