0

I have 4 data matrices 50x35 double (Diff_CT, Diff_Imp, Diff_F1, Diff_F2)

I have calculations to perform strictly identical for each of these matrices and suddenly I would like to create a for loop in which part of the name of the matrices is the input parameter

An example of what I tried but did not succeed

parameters = {'CT', 'Imp', 'F1', 'F2'};

for i_parameters = 1: numel(parameters)
    my_parameters = parameters{i_parameters};

    ['Diff_',(my_parameters),'_T0'] = ['Diff_',(my_parameters)](:,1) ['Diff_',(my_parameters)](:,8) ['Diff_',(my_parameters)](:,15) ['Diff_',(my_parameters)](:,22) ['Diff_',(my_parameters)](:,29)];
    ['DiffMean',(my_parameters),'0'] = mean(mean(['Diff_',(my_parameters),'_T0'));
    ['Diffstd',(my_parameters),'0'] = std(std(['Diff_',(my_parameters),'_T0'));
end
1
  • You should not be using multiple named matrices for this exact reason - it is not possible to elegantly loop over them. Rearrange your data using cell arrays or structs, instead. Commented Jun 17, 2018 at 18:13

1 Answer 1

1

There is never a good reason to create dynamic variable names. One of the problems they create is what you're experiencing. Use structs/ cell arrays/ ND arrays; whichever suitable for the situation. In your case, struct seems to be more suitable as shown below:

%Converting your data matrices into a struct
Diff_ = struct('CT',Diff_CT, 'Imp',Diff_Imp, 'F1',Diff_F1, 'F2', Diff_F2);  

for i_parameters = 1 : numel(parameters)       
    my_parameters = parameters{i_parameters}; 

    %Creating structures with your variables as their fields        
    Diff_.([my_parameters '_T0']) = [Diff_.(my_parameters)(:,1)  ...
        Diff_.(my_parameters)(:,8)  Diff_.(my_parameters)(:,15) ...
        Diff_.(my_parameters)(:,22) Diff_.(my_parameters)(:,29)];

    DiffMean.([my_parameters '0']) = mean(mean(Diff_T0.(my_parameters)));
    Diffstd.([my_parameters '0'])  = std(std(Diff_T0.(my_parameters)));
end

What you were expecting to have as the variables Diff_CT_T0, DiffMeanCT0 and DiffstdCT0 can now be accessed as Diff_.CT_T0, DiffMean.CT0 and Diffstd.CT0 respectively and so on.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.