Matlab: In for loop, change name of variable
    4 views (last 30 days)
  
       Show older comments
    
Hi!
I have a variable (vector of size 101x1) in a for loop, named input_reec_PGC1. It is imported from the input_consigne_egal_mesure; on the second line of my code (below).
I define another variable (also vector 101x1), named new_input. Now, I would like to write input_reec_PGC1 = new_input.
My code below works, however, I would like for the input_reec_PGC1 to be programatically generated, from the variable nom_parametre_variant (4th line of code), as I did for the variable variation_du_parametre (5th line of code).
Indeed, I need to do a large number of simulations and the less I  need to change my code the better, so I would like the user only to have to write down the nom_parametre_variant and from there the code does the rest.
I tried 
eval(['input_', nom_parametre_variant ]) = new_input; 
but get the error:
In an assignment  A(I) = B, the number of elements in B and I must be the same.
I have the following code:
clear;
input_consigne_egal_mesure;
variation_parametres;    
nom_parametre_variant = 'reec_PGC1';
variation_du_parametre = eval(['var_',nom_parametre_variant]);
name_output_file = [nom_parametre_variant, '.csv'];
name_output_folder = char(['results_',nom_parametre_variant]);
if ~exist(name_output_folder, 'dir')
    mkdir(name_output_folder)
end
% pwd: current path 
path_to_results_folder = [pwd,'/',name_output_folder];
path_to_output_file = fullfile(path_to_results_folder, name_output_file);
solutions = zeros(1000,length(var_VGO)*4);
colonne = 1;
for i = 1 : numel(variation_du_parametre);
    % On change le parametre variant
    disp(['Variation: ',num2str(variation_du_parametre(i))]);     
    %% ISSUE HERE
    % new_input = variation_du_parametre(i) * ones(1, length(t));
    input_reec_PGC1 = variation_du_parametre(i) * ones(1, length(t));
    input_reec_PGC1 = new_input;
    %%
    options = simset('SrcWorkspace','current') ;
    sim('mon_modele_INES.slx',temps_simulation, options);
    solutions(:, colonne:1:colonne+3)=yout;
    colonne = colonne + 5;
end
Thank you in advance for your help!
0 Comments
Answers (1)
  Jan
      
      
 on 24 Nov 2021
        This is a very bad idea. The severe problems caused by the dynamic creation of variables have been discussed in the forum exhaustively. See: TUTORIAL: Eval
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
