Robert Seifert
Robert Seifert

Reputation: 25232

Add field to existing struct or variable via function without renaming or destroying the original struct

Imagine the following struct:

A.B1 = 1:42;
A.B2 = 'Hello World!'

Now I want to do some operations, but backup the existing data in a new substruct.

A.B1.C1 = A.B1;
A.B1.C2 = mean(A.B1.C1);

These two lines (as an example) I want to put into a function, so my script would look as follows:

A.B1 = 1:42;
A.B2 = 'Hello World!'
myfunction(A.B1)

and my workspace should afterwards look like:

A = 

    B1: [1x1 struct]
    B2: 'Hello World!'

A.B1 =

    C1: [1x42 double]
    C2: 21.5

But I can't manage to create that function that way, that my original struct A is not destroyed. Apart from that the input to my function could be W.X.Y and I'd like to get W.X.Y.Z1 and W.X.Y.Z2 afterwards. And also it could be a simple vector A = 1:42 and should be A.B1 and A.B2 afterwards.

Any advices?

I could build something ugly with fieldnames and assignin('base',...) - but is this really the way to go?


Edit: One of the major problems is also that the function inputname is not working for structs. So If I pass A to my function, I could then use fieldnames to get the names of B1 and B2, but I can't find out what is the initial fieldname "A". If A would be variable inputname(1) in my function would return 'A'. For structs the output is empty.


Would classes and methods be the solution? Unfortunately I'm not familiar with OOP at all...

Upvotes: 4

Views: 3438

Answers (1)

Vuwox
Vuwox

Reputation: 2359

The only thing I see can be something like that :

function [out] = myfunction(in)

    out.base = in;
    out.compute = mean(in);

end

And when you want to work with your function you have to provide same input/output variable like this :

A.B1 = 1:42;
A.B2 = 'Hello World!'
A.B1 = myfunction(A.B1);

Also possible for multiple inputs:

function [varargout] = myfunction(varargin)

for ii = 1:nargin

    out.base = varargin{ii};
    out.compute = mean(out.base);
    varargout{ii} = out; 

end

end

as long as output variables are equal in notation to their according input variables:

W.X.Y1 = 1:42;
W.X.Y2 = 'Hello world!';

A.B1 = 100:-1:0;
A.B2 = 'Goodbye cruel world!' 

[W.X.Y1,A.B1] = myfunction(W.X.Y1,A.B1)

Upvotes: 3

Related Questions