MATLAB Answers


including subject_name in variable with a loop

さんによって質問されました 2012 年 3 月 20 日
Dear all,
We are running a script over several subjects in order to get mean reaction time data per condition out of each of them independently.
We have a simple loop:
subject = {subject_1 subject_2 subject_3 ...}
for i = 1: (length(subject))
... run the script
and here we would like to save our results in a new variable whose name would be accordingly "subject_1", "subject_2" and so on.. For example:
final_subject_1 = [mean1 mean2 mean3 mean4]
We thank you very much for any suggestion!

  0 件のコメント

サインイン to comment.

3 件の回答

回答者: Grzegorz Knor 2012 年 3 月 20 日

eval(['final_subject_' num2str(i) '= [mean1 mean2 mean3 mean4]'])

  2 件のコメント

2012 年 3 月 20 日
Right it works, Grzeg, but we forgot to add that our subjects have strings like "WRDF" or "RWEX" and so on..
subject = {WRDF RWEX DFGR ..}
so the num2str function is not useful here..
We just used subject_1, subject_2 for making it easier to understand (but appartently it was not..) Sorry!
How would you proceed then?
Daniel Shub
2012 年 3 月 20 日
Conceptually it is the same thing. Just replace num2str(i) with subject{i}.

サインイン to comment.

Daniel Shub
回答者: Daniel Shub
2012 年 3 月 20 日

You can do it with eval, but then in a few days you will be back asking how to use the variables. This is a FAQ, and is generally not a good idea ...

  0 件のコメント

サインイン to comment.

回答者: Geoff
2012 年 3 月 20 日

This has already been solved for you, but I'll chip in.
In this case, there doesn't appear to be a good reason to use dynamic names. Why not put all your data into matrix form in the same order as the subjects?
means = zeros(length(subject), 4);
for row = 1:length(subject)
% do your stuff...
means(row,:) = [mean1 mean2 mean3 mean4];
If you're concerned about looking up a subject, make a quick helper function:
subject = { etc etc etc }; % This needs to come first.
find_subj = @(name) find( cellfun(@(s) strcmp(s,name), subject) );
Now, the means for subject_2:
means( find_subj('subject_2'), : )
This approach is far more flexible than using dynamic names. Consider this: how were you intending to plot your results?

  3 件のコメント

Daniel Shub
2012 年 3 月 20 日
+1 Well said. What do you mean by dynamic names? I typically think of dynamic names as being: data.('subject_1') = [mean1, mean2];
2012 年 3 月 20 日
Yeah I guess that's the proper term for that specific syntax. But I just meant any situation where you create a variable (or field) using a name that is set at runtime. I'm a MatLab newbie so I may be a bit loose with terminology. =)
Daniel Shub
2012 年 3 月 25 日
That is a fine use of "dynamic names", I just wanted to check to make sure I understood.

サインイン to comment.

Translated by