2

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?

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

It is way better than the arrayfun() (~3seconds to ~30 seconds), but i would like to avoid for loops, as there might be a way to handle this as array. neverless Thank You, i will take this solution if no other is possible
You might be able to try doing something like [Data(:).Date]=arr, but I don't have a copy of Matlab to verify this with.
2

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{:};

1 Comment

Thank you, well this is just swell. I checked the performance of both given solutions against my old arrayfun approach. for who is intrested on performing datetime on 50000 entries: arrayfun - 23sec for loop - 3.3sec num2cell - 3.3sec both solution appear to have the same performance but i am going to stick to the num2cell as, as mentioned, i would like to avoid loops in the code. Again Thank you both

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.