Argyll
Argyll

Reputation: 9875

Is there a way to convert a double array to a struct array?

Is there a way to convert a double array to a struct array and place it under one field?

For example, suppose we get a double array from a call of cellfun and the output array looks like

data=[1,2;3,4];

Can we get a struct S where

S=struct;
for i=1:numel(data)
        S(i).data=data(i);
    end
end

with native functions or just get S efficiently? (visual at the end)

If there is a method, can the resultant struct array preserve the dimensions of the original double array? Can the method apply to output of cellfun where the output is a double array?

In my particular application, my data is the (uniform) output of a call to cellfun and when I set S.data=cellfun(...), the result is a 1-element struct array where S.data is the m-by-n double array from cellfun(...). What can I do to distribute the array elements?

(My task at hand involves processing 10k data points per query and for each task, it's about 16 queries. So speed is important. If there is no efficient method, I'll know to avoid struct for this particular type of tasks. So comments on that front is helpful too.)

enter image description here

Upvotes: 0

Views: 2597

Answers (2)

rahnema1
rahnema1

Reputation: 15837

Use struct and num2cell:

data = [1,2;3,4];
S = struct ('data', num2cell(data));

Upvotes: 2

Max
Max

Reputation: 4045

As you want to have an individual field for every element of the matrix, I have to say: no there is no standard solution for this. If you don't absolutely need it, I would not recommend doing so, see this post. It simply requires more memory and is a bit of a pain when looking.

Nevertheless, it is possible but you have to start each name of your field with a character.

data = [1,2;3,4];
% create empty struct
S = struct();
%% create new structure
for i = 1:length(data)
    % create field name (must start with a character!)
    fld = num2str(i,'F%d');
    % write to field (note the brackets)
    S.(fld) = data(i);
end

I case, you want o access the data by looping, use the MATLAB-buildin function fieldnames for a more general approach than building the filed names by yourself (and avoid shortfalls, when your delete one field;) )

%% access new structure (looping over field names)
% get all field names
FlNms = fieldnames(S);
for i = 1:length(FldNames)
    % access field names (this is a cell!)
    fld = FldNms{i};
    % access struct
    data_element = S.(fld);
    % do something
end

Upvotes: 0

Related Questions