For loop with dynamic variable name condition

11 ビュー (過去 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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by