Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing variable names dynamically

Tags:

loops

matlab

I have a loop that calculates the mean (m), standard deviation (std), and standard error (sem) for multiple conditions. As each condition has its own m, std, and sem and I would like to name my output accordingly (they should be in double format). For example: cond1_m, cond1_std, cond1_sem, cond2_m, cond2_std, cond2_sem etc.

This is what I tried:

    cond={'cond1','cond2','cond3','cond4','cond5',...}
    for a=1:length(cond) 
        [strcat(cond{a},'_m'),strcat(cond{a},'_std'),strcat(cond{a},'_sem')]=compute_stats(M(:,a));
    end

Note: compute_stats is the function that outputs m, std, and sem. M is the matrix containing my data. The issue is that the strcat doesn't seem to work as a way of changing the name of my output. For iteration 1, for instance, instead of giving me cond1_m, my output is a matrix named strcat.

Can anyone help?

like image 437
A.Rainer Avatar asked Jun 07 '26 01:06

A.Rainer


1 Answers

Consider using a structure instead which is very suitable for your purposes. BTW, do not use cond as a variable name. There is a function called cond that calculates the condition number of a matrix. Using cond in this case would overshadow this function. You can leave the cond1, cond2, etc. fields the way they are:

con={'cond1','cond2','cond3','cond4','cond5',...};
result = struct();
for a=1:numel(con)
    [m, stdd, sem] = compute_stats(M(:,a));
    result.([con{a} '_m']) = m;
    result.([con{a} '_std']) = stdd;
    result.([con{a} '_sem']) = sem;
end

result contains your desired compiled results. You would then access the right matrix using the correct string name. For example, if you wanted the std output for the first condition, do:

out = result.cond1_std;
like image 68
rayryeng Avatar answered Jun 10 '26 19:06

rayryeng