MATLAB: Generate new variables based on expressions in structure array using loops — example provided need help to fix

expressionsgenerate new variables

Can someone help direct me on how to get this to work? For example, I would like to create a new variable in the 'var' structure array that identifies the last year for each cell array and then assigns the last value in the data variable.
var.time = cell(4,1);
var.time{1,1}={'2011';'2012';'2013';'2014'};
var.time{2,1}={'2011';'2012';'2013'};
var.time{3,1}={'2011';'2012'};
var.time{4,1}={'2011';'2012';'2013';'2014';'2015'};
var.data{1,1} = {1;2;3;4};
var.data{2,1} = {1;2;3};
var.data{3,1} = {1;2};
var.data{4,1} = {1;2;3;4;5};
[m,n] = size(var.time);
for j = 1:m;
varName{j,1} = ['var.',var.time{j,1}{end,1},'{',num2str(j),'}'];
var.(varName{j,1}) = var.data{j,1}{end,1};
end

Best Answer

  • I'm a bit confused by what you're asking as you seem to have the answer in your question. It's just that the name you generate is not a valid field name because of the dot.
    To create / use a field whose name you generate from an expression, use dynamic field names which are enclosed in brackets:
    for year = [2011 2012 2013]
    fname = sprintf('Min%d', year);
    s.(fname) = year;
    end
    If you end up creating field names that are not valid, you can transform them into valid field names with genvarname.