Reputation: 409
I am trying to assign a vector of doubles to a structure.
I have a structure Struct1(1).Data(1:end).Date
that holds 4030 NaN
values. I have a vector of doubles called Dates
that contains 4030 dates stored as doubles. How can I assign Dates
to Struct1(1).Data(1:end).Date
?
In general, I seem to be having a problem understanding how to make assignments between structures, vectors, and cell arrays (I don't understand the use of (
vs {
vs [
). Can someone please tell me how I can resolve the specific issue described above and/or point me to a good description of what I'm trying to accomplish with clear examples?
Upvotes: 1
Views: 1469
Reputation: 2187
Ultimately you need a comma separated list in order to cleanly assign into each value of the structure array. However, double values do not return a comma separated list but rather just the array itself or some subset. To do so you need to convert your vector of doubles into a cell array first in order to get each value of the vector into its own independent cell that can be "dealt" to each array of the structure. You can do this with num2cell. For example:
% Setup the data (also uses the num2cell technique)
nans = num2cell(NaN(1,4030));
s = struct;
[s.Data(1:numel(nans)).Date] = nans{:}
% Now assign valid data (note that since the structure is already allocated
% to the right size we can just use (:)
dates = num2cell(rand(size(s.Data)));
[s.Data(:).Date] = dates{:}
This page has some good info about comma separated lists and their relation to structs, cells, and dealing their output values in this way.
Upvotes: 3
Reputation: 18484
I feel like you're really abusing struct arrays. You may want reconsider the organization of your data. You might find this video from the MathWorks helpful (the comments too).
First let's build up an example struct array of struct arrays as you have it
Struct1 = struct;
Struct1.Data = struct;
for i = 1:3
Struct1(1).Data(i).Date = rand(1,9); % Random values instead of dates for demo
end
All three Date fields can be output into one cell array via
dates = {Struct1(1).Data(:).Date}
this gives:
dates =
[1x9 double] [1x9 double] [1x9 double]
You can transpose these or concatenate them into a a single matrix if all of the cells are of the same size.
Now if you want to change the values stored in each instance of Date, you can use:
dates2 = {rand(4,1),rand(5,1),rand(6,1)}; % Create new cell array of random data
[Struct1(1).Data(:).Date] = dates2{:}; % set cell contents to each field
Now, outputting as a cell array again (dates3 = {Struct1(1).Data(:).Date}
) returns what you just stored
dates3 =
[4x1 double] [5x1 double] [6x1 double]
Yes, it's quite messy and confusing.
Upvotes: 2