For loop with dynamic variable name condition

10 vues (au cours des 30 derniers jours)
Ignacio Lobato
Ignacio Lobato le 27 Avr 2015
Modifié(e) : Stephen23 le 19 Juin 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 commentaire
Guillaume
Guillaume le 27 Avr 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.

Connectez-vous pour commenter.

Réponses (1)

Stephen23
Stephen23 le 12 Jan 2016
Modifié(e) : Stephen23 le 19 Juin 2019

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by