user3887089
user3887089

Reputation: 307

Nested For Loop to build a struct

I would like to build a nested struct using a nested for loop. The structure I want would first split according to direction (one of 8 directions), and then each direction would have two fields. I have tried something like:

for i=1:8
    data(i).direction=i;
    for j=1:numTrials
         data(i).direction(j).sp_time=spikeTimes
         data(i).direction(j).sm_time=smoothedTimes
    end
end

I get an error saying "Field assignment to a non-structure array object". I need to use the nested for loop because other data manipulation is happening inside the for loops to give me the values for spikeTimes and smoothedTimes. I've read the documentation for creating structs, but can't figure out how this nested struct can be constructed inside the for loops.

Upvotes: 0

Views: 1011

Answers (1)

EelkeSpaak
EelkeSpaak

Reputation: 2825

How about this:

for i=1:8
    % initialize to empty struct, rather than number
    data(i).direction = struct();
    for j=1:numTrials
         data(i).direction(j).sp_time=spikeTimes
         data(i).direction(j).sm_time=smoothedTimes
    end
end

Upvotes: 3

Related Questions