How to access elements of a structure without the use of a loop ?
Mostrar comentarios más antiguos
Hi everybody,
my question sounds very simple but I cant find a way to have access to elements (values) of a structure without a loop. Here below is what I have done with the help of a loop:
for i=1:length(conf.running)
event1LFS(i)=Running{i}.SP.LFS2LMS;
end
event1LFS=mean(event1LFS);
So if you have a way like the following one (but this one does not work of course), it would be perfect. Thank you
event1LFS=mean(Running{1:end}.SP.LFS2LMS);
2 comentarios
Adam
el 29 de Abr. de 2015
It would help if you could give a small example of the cell array structure for us to test on as I don't have time personally to try to create a test array that fits the criteria, but don't mind taking a quick look with some actual data.
Vincent
el 29 de Abr. de 2015
Respuesta aceptada
Más respuestas (2)
James Tursa
el 29 de Abr. de 2015
Editada: James Tursa
el 29 de Abr. de 2015
Try this: EDITED
temp1 = [Running{:}]; % Extract the cells, concatenate into a single struct array
temp2 = [temp1.SP]; % Extract 1st level field and concatenate
event1LFS = mean([temp2.LFS2LMS]); % Extract 2nd level field, concatenate, take mean
3 comentarios
Vincent
el 29 de Abr. de 2015
Stephen23
el 29 de Abr. de 2015
Sadly nested structures do not allow the extraction of all field values into a comma separated list, so the [temp.xxx.yyy] syntax does not work.
James Tursa
el 29 de Abr. de 2015
Thanks ... that means an extra step. I have edited my Answer to reflect this.
You can do this without any loops or cellfun if you rearrange the data a little bit. The following two changes would need to be made:
- use a non-scalar structure instead of a cell array holding individual scalar structures.
- do not nest structures within other structures.
After these two changes you could simply do this:
mean([Running.LFS2LMS])
which is much faster and more efficient that any playing around with cell arrays and the like. Here is a simple example showing how accessing non-scalar structure can work:
>> A(3).data = 8;
>> A(2).data = 4;
>> A(1).data = 2;
>> mean([A.data])
ans =
4.6667
And that is it: no cell arrays, no functions, no complications... just fast and simple.
3 comentarios
Vincent
el 29 de Abr. de 2015
Vincent
el 29 de Abr. de 2015
If Running is a non-scalar structure then the syntax
Running.SP
Running(1).SP,Running(2).SP,Running(3).SP,...
But you only assign the first one to a variable, which is basically the same as doing this:
temp = Running(1).SP
This is why I clearly state in my answer "2. do not nest structures within other structures.".
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!