Finn
Finn

Reputation: 2343

Accessing multiple Fields in a matlab struct

I am trying to acces multiple fields in an struct to change the data from datenum to datetime. The struct is created by:

    DATA=struct('Id',[],'Date',[],'Value',[]);

and due to the style of receiving the Data, there are multiple DATA with each having one Value. So a sufficent example would be

    Data(1).Date=2;
    Data(2).Date=3;

now i would like to change the entry to datetime but leaving the data structure as it is. FOr the example lets say to square the date to.

    Data(1).Date=4;
    Data(2).Date=9;

The struct has about 50000 enries and arrayfun() does not give an efficient enough solution. I cant find a way to convert the entire array of Data.Date ad once deal() write all 50000 dates in each field and in every other way i receive errors. Does someone has a solution to change the entire array and write it back in each Field of the array?

Upvotes: 2

Views: 1018

Answers (2)

Daniel
Daniel

Reputation: 36710

Using a small detour converting form struct to array, then do the math, then convert from array to cell to comma separated list to a struct:

arr=[Data(:).Date];
arr=num2cell(arr.^2);
[Data(:).Date]=arr{:};

Upvotes: 2

Tim Adams
Tim Adams

Reputation: 156

You could put all of the values into an array and then repopulate the structure after calculating the results.

arr=[Data(:).Date];
arr=arr.^2;
for a=1:numel(arr)
   Data(a).Date=arr(a);
end

Upvotes: 3

Related Questions