extract structure array value

3 visualizaciones (últimos 30 días)
Murugan C
Murugan C el 24 de Sept. de 2020
Comentada: Murugan C el 1 de Oct. de 2020
Hi all
I have nested structure like below,
MyData(1).User.Id = 5;
MyData(1).User.Name = 'XXX';
MyData(2).User.Id = 7;
MyData(2).User.Name = 'XXX';
MyData(3).User.Id = 8;
MyData(3).User.Name = 'XXX';
MyData(4).User.Id = 9;
MyData(4).User.Name = 'XXX';
MyData(5).User.Id = 75;
MyData(5).User.Name = 'XXX';
MyData(6).User.Name = 45;
MyData(6).User.data = 'XXX';
I need output out = [5,7,8,9,75,45]
without loop i need to output.
if any body know inbuild command for that.
Thanks in advance.
  2 comentarios
Stephen23
Stephen23 el 24 de Sept. de 2020
After fixing the mismatching fieldnames, you can use comma-separated lists like this:
>> tmp = [MyData.User];
>> out = [tmp.Id]
out =
5 7 8 9 75 45
Murugan C
Murugan C el 1 de Oct. de 2020
It work fine... Thanks

Iniciar sesión para comentar.

Respuesta aceptada

Rik
Rik el 24 de Sept. de 2020
Editada: Rik el 24 de Sept. de 2020
You can hide the loop with arrayfun, but be aware that a good loop is always better than cellfun or arrayfun. You should ask yourself why you want to avoid loops.
MyData(1).User.Id = 5;
MyData(1).User.Name = 'XXX';
MyData(2).User.Id = 7;
MyData(2).User.Name = 'XXX';
MyData(3).User.Id = 8;
MyData(3).User.Name = 'XXX';
MyData(4).User.Id = 9;
MyData(4).User.Name = 'XXX';
MyData(5).User.Id = 75;
MyData(5).User.Name = 'XXX';
MyData(6).User.Id= 45;%correcting assumed typo
MyData(6).User.Name= 'XXX';%correcting assumed typo
arrayfun(@(s) s.User.Id,MyData)
It is also possible to avoid arrayfun:
tmp=[MyData.User];[tmp.Id]
%R2020a and later:
[horzcat(MyData.User).Id]

Más respuestas (2)

madhan ravi
madhan ravi el 24 de Sept. de 2020
You need to use a loop.

Fangjun Jiang
Fangjun Jiang el 24 de Sept. de 2020
%% correct data first
MyData(6).User.Id= 45;
MyData(6).User.Name= 'XXX';
%% then
A=struct2array(MyData);
result=[A.Id];

Categorías

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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by