Matlab: access to one element in all folded structures

I have a complex data structure that looks something like this:

a(1) = struct('X',rand(10,1),'Y',rand(10,1),'Time',(1:1:10)') a(2) = struct('X',rand(10,1),'Y',rand(10,1),'Time',(1:1:10)') 

(The number of stack structures and the length of each parameter are not constant)

Now I would like to access all X data with a timestamp of 5. I know that I can do this with a loop:

 data = zeros(length(a),1) for k=1:1:length(a) data(k) = a(k).X(5) end 

But I wonder if there is no way to access data without a loop?

I tried b = [ a(:).X(5) ] , but this does not work ( b = [ a(:).X ] does). I should already do this in an environment loop, so I would like to avoid unnecessary calculations ...

And in the same section: is it possible to get all the data of one stack with the same timestamp? Something like that:

 data = a(1)(a(1).Time==5) >> data data = <X value> <Y value> 5 

Thank you for your help!

+4
source share
3 answers

This is exactly what getfield for!

 data = getfield( a, {1:numel(a)}, 'X', {5} ); 
+4
source

What about

 allDataX = [a(:).X]; allDataX(5, :) % the fifth row of all the Xs 

As for your second question, you can do something like this

 allTimes = [a.Time]; allDataX(allTimes == 5) 
+1
source

One liner solution

Equivalent to [a(:).X(5)] , you can use subsref() to execute [aX](5,:) :

 subsref([aX], substruct('()',{5,':'})) 

Similarly, a(1)(a(1).Time == 5) can be performed using [a(1).X a(1).Y a(1).Time](a(1).Time == 5,:) :

 subsref(cell2mat(struct2cell(a(1))'), substruct('()',{a(1).Time == 5,':'})) ans = 0.6324 0.8003 5.0000 

Best approach

I assume that each timestamp has a pair of coordinates, which means that you can save your structure as:

 data = [a(1).X a(1).Y a(1).Time]; 

This will make indexing easier:

 data(:,5) data(data(:,3)==5,:) 

You can store different sets of coordinates in an array of cells:

 data = {[a(1).X a(1).Y a(1).Time] [a(2).X a(2).Y a(2).Time] ...}; data{1}(:,5) data{1}(data{1}(:,3)==5,:) 
+1
source

Source: https://habr.com/ru/post/1482156/


All Articles