MATLAB: Creating new fields in multiple structures with loops

loopsstructures

Hi all
I have some data in the form of structures, eg strA, strB e.t.c. All structures have the same fields, let's say f1 and f2. I want to create the same new fields in every structure, for example:
strA.mean = mean(strA.f1);
strA.std = std(strA.f1);
Is there a way to do this with a loop so I don't have to write the above two lines of code for each structure? I tried the following but it doesn't work:
structnames = {'strA','strB','strC','strD','strF','strG','strK'}
n = length(structnames)
for i = 1:n
structnames{i}.mean = mean(structnames{i}.f1);
structnames{i}.std = std(structnames{i}.f1);
end
Any ideas?

Best Answer

It is never a good idea to name your variables like strA, strB, strC, ... There is a done of discussion on this topic explaining why it is an inefficient and dangerous: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. A better strategy is to create an array of struct accessible as str(1), str(2), str(3), ...
Although it is possible to do what you asked in your question, I will not be a part of this sin ?and only show you a way to create a struct array. After that, you can easily add a new field to all the fields to all the elements of the array.
strA.f1 = rand(1,10);
strA.f2 = rand(1,10);
strB.f1 = rand(1,10);
strB.f2 = rand(1,10);
% create the array of struct
clear str
vars = whos('str*');
str(numel(vars)) = struct('f1', [], 'f2', []);
for i=1:numel(vars)
str(i) = eval(vars(i).name);
end
% see how easy it is now
for i=1:numel(str)
str(i).mean = mean(str(i).f1);
str(i).var = var(str(i).f1);
end