Borrar filtros
Borrar filtros

How do structures work?

1 visualización (últimos 30 días)
Chiara Modenese
Chiara Modenese el 13 de Abr. de 2011
Hi there. Say that I use an array of structures and that then I want to create an array like:
[ss.phi] % ss is the array of structures, and phi a number
Now, the above works just fine but what does not work is:
[ss.phi(1)] % this time phi is an array of doubles and I only want to keep the first element
Why is the last case wrong? And how to fix it?
Thanks. Chiara

Respuestas (2)

Jarrod Rivituso
Jarrod Rivituso el 13 de Abr. de 2011
I think MATLAB doesn't let you nest subscripts like that. However, there are workarounds. Is this what you are looking for:
>> var(1).a = [3 4];
>> var(2).a = [5 6];
>> var(1).b = 10;
>> var(2).b = 13;
>> getFirstElementFcn = @(x) x(1);
>> allFieldsA = {var.a};
>> cellfun(getFirstElementFcn, allFieldsA)
  1 comentario
Jarrod Rivituso
Jarrod Rivituso el 13 de Abr. de 2011
Note that I've created an anonymous function to go through and grab the first element, and then I've put all the field values in a structure array, and then finally I apply the function to the field values within the cell.

Iniciar sesión para comentar.


Oleg Komarov
Oleg Komarov el 13 de Abr. de 2011
ss.phi = rand(10);
ss.phi = ss.phi(1)
Saying it's not working is as far as you can get from a clear description of a problem.
EDIT Following Jarrod's interpretation (which by the way, I now think, is your situation), another way:
var(1).a = [1 2; 3 4];
var(2).a = [5 6; 7 8];
temp = cat(3,var.a);
squeeze(temp(1,1,:))
Or fetching elements in a loop (no vectorized way available):
% Preallocate
...
for s = 1:numel(var)
out(...) = var(s).a(1)
end
  1 comentario
Chiara Modenese
Chiara Modenese el 13 de Abr. de 2011
Well, this is not what I would exactly define as a satisfactory answer. However, I can see there are many workarounds (thanks to Jarrod, too).
Chiara

Iniciar sesión para comentar.

Categorías

Más información sobre Structures en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by