MATLAB: How to use structure properly

structure

Hi all,
I have a newbie question, how to use structural variable properly? A minimum example:
clear; clc;
no.inpt = 5;
inpt.a1 = rand(no.inpt);
inpt.a2 = rand(no.inpt);
inpt.a3 = rand(no.inpt);
[otpt] = teststruct(inpt);
[otpt] = teststruct1(otpt);
where the two functions are:
function [otpt] = teststruct(inpt)
otpt.x = inpt.a1 + 3 * inpt.a2 - inpt.a3;
otpt.y = 2 * inpt.a3;
and
function [otpt] = teststruct1(inpt)
otpt.z = inpt.x * 2 + inpt.y * 3;
After this, variable otpt only contains one subfield z which I understand that teststruct1 regenerate otpt. However, what I want is to let otpt keep three subfields x, y and z without renaming otpt after function teststruct. How could I achieve it?
Many thanks!

Best Answer

Have a look at these two lines:
[otpt] = teststruct(inpt);
[otpt] = teststruct1(inpt);
the first line creates otpt in that workspace, but then you never use this structure and on the second line the entire structure is thrown away because you define a new variable (which also happens to be a structure) using the same name. This has nothing to do with structures, you are just reallocating the same variable name.
Here are some ways to get the effect that you want:
  1. return a variable from the function, allocate it to a structure field: otpt.z = fun(...);.
  2. use one of the "merge structure" utilities on MATLAB FEX, e.g. catstruct.
  3. supply the structure as an input, add the field internally, and return it again:
function otpt = fun(otpt,inpt)
otpt.z = ...
end
personally I would use the last option: fast, neat, intuitive.