3

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?

rayryeng
  • 102,964
  • 22
  • 184
  • 193
A.Rainer
  • 719
  • 5
  • 16

1 Answers1

7

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;
rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • Thank you. I did try to use a structure but insisted on using strcat (i.e., result.(strcat(cond{a},'_m') and clearly that didn't work. – A.Rainer May 05 '16 at 21:30
  • @A.Rainer Ah :). Make sure you encapsulate the string with `[]` or it won't work when it comes to dynamically creating fields in structures. – rayryeng May 05 '16 at 21:31