How do I assign a function output (in the form of a vector) to a field for a vector of structures?

6 views (last 30 days)
Dear All I have a database in the form of a vector of structures (see “GHG” in script). I start with data for each struct element - which covers 4 fields. I wish to pass data from the 4 fields into functions. I then wish to pass the outputs from the function. I want to use the function outputs as the data for new fields that I assign to the original vector of structures. I choose to assign the data because at this early stage I am not sure how many new fields I want to assign. If I knew I would think about defining these new ones as empty fields in the original structure. I am aware the empty field method is computational more efficient. I am relatively new to MatLab and have been unable to correct my code which returns an error “Incorrect number of right hand side elements in dot name assignment. Missing [] around left hand side is a likely cause.” My Base script is:
GHG = repmat(struct('Gas_name','CO2','pre', 200, 'current', 400),4:1);
GHG(2) = struct('Gas_name','CH4','pre', 200, 'current', 400);
GHG(3) = struct('Gas_name','N02','pre', 200, 'current', 400);
GHG(4) = struct('Gas_name','Lin_gas','pre', 200, 'current', 400);
% Call anad execute the function calculating Excess emissions at the baseyear
EXC = calcEXC([GHG.current], [GHG.pre])
% Now assign the new information generated in the calcEXC function to a new field in GHG called EXC
EXC = calcEXC([GHG.current], [GHG.pre])
GHG.EXC = EXC
My Function
function EXC = calcEXC(a, b)
% Caclulates the GHG concentration in excess of pre-ind levels
[EXC] = a - b
End
The error message
Incorrect number of right hand side elements in dot name assignment. Missing [] around left hand side is a likely cause.
Error in two_structures (line 48)
GHG.EXC = EXC
Thank you for your help

Accepted Answer

Stephen23
Stephen23 on 5 Feb 2016
Edited: Stephen23 on 5 Feb 2016
% Create non-scalar struct from cell arrays:
name = {'CO2','CH4','NO2','Lin_gas'};
preV = { 200, 200, 200, 200};
curV = { 400, 400, 400, 400};
GHG = struct('Gas_name',name,'pre',preV,'current',curV);
% Define anonymous function:
calcEXC = @(a,b) a-b;
% Calculate and allocate into structure:
tmp = num2cell(calcEXC([GHG.current],[GHG.pre]));
[GHG.EXC] = tmp{:};

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!