matlabmatlab-struct

Is there a way to remove all but a few desired fields from a struct in MATLAB?


So I have several structs that contains data that is used is a dozen or so scripts. The problem is that for each script I only need a handfull of variables and the rest I can ignore. I am using a massive amount of data (gigs of data) and MATLAB often gives me out of memory errors so I need to remove all unnecessary fields from the structs.

Currently I have a cell that contains all unneeded fields and then I call rmfield on the structs. But the fields in the structs often change and it is getting to be a pain to be constantly updating the list of unneeded fields. So is there a way to tell MATLAB to keep only those fields I want and remove everything else even if I don't know what everything else is?

Here is an example,

Sometimes Struct 3 might only have A thru G.

I want to keep only A, B, and C fields and remove all other data from all the structs.


Solution

  • You could copy your struct's desired fields to a new variable in a function.

    function newVar = getABC(strct)
        newVar.A = strct.A;
        newVar.B = strct.B;
        newVar.C = strct.C;        
    end
    

    strct will not be copied in memory beacuse you will not be manipulating it.

    MATLAB uses a system commonly called "copy-on-write" to avoid making a copy of the input argument inside the function workspace until or unless you modify the input argument. If you do not modify the input argument, MATLAB will avoid making a copy.

    You can get newVar and then clear strct from memory.


    Fred's generalized version:

    function newVar = getFields(oldVar, desiredCell)
        for idx = 1:length(desiredCell)
        newVar.(desiredCell{idx}) = oldVar.(desiredCell{idx});
    end