Add a field to an existing structure or variable through a function without renaming or destroying the original structure

Imagine the following structure:

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

Now I want to perform some operations, but back up existing data in a new substructure.

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

These two lines (as an example) I want to add to the function, so my script will look like this:

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

and my workspace should look like this:

A = 

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

A.B1 =

    C1: [1x42 double]
    C2: 21.5

But I am unable to create this function in such a way that my original structure is Anot destroyed. In addition, the entrance to my function can be W.X.Y, and I would like to receive W.X.Y.Z1and W.X.Y.Z2then. And also it can be a simple vector A = 1:42and should be A.B1, and A.B2subsequently.

Any tips?

- fieldnames assignin('base',...) - ?


: , inputname . , A , fieldnames, B1 B2, , "A". A inputname(1), 'A'. structs .


? , ...

+4
1

, , :

function [out] = myfunction(in)

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

end

, ​​ /, :

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

:

function [varargout] = myfunction(varargin)

for ii = 1:nargin

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

end

end

:

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)
+3

All Articles