When i covert a structure to cell array, my fieldNames disappear

3 visualizaciones (últimos 30 días)
Shambhavi Adhikari
Shambhavi Adhikari el 10 de Mzo. de 2021
Editada: Jorg Woehl el 11 de Mzo. de 2021
I am trying to convert a structure to a cell array, when i do that, i am not able to see field on my new cell array, i only see values. Is there a way to have both field and values on the cell array?

Respuestas (3)

Fangjun Jiang
Fangjun Jiang el 10 de Mzo. de 2021
There is no meta data text info for cell array. Use struct2table() to convert structure to table.
  2 comentarios
Shambhavi Adhikari
Shambhavi Adhikari el 10 de Mzo. de 2021
Error using table.fromScalarStruct (line 480)
Fields in a scalar structure must have the same number of rows.
Error in struct2table (line 65)
t = table.fromScalarStruct(s);
Shambhavi Adhikari
Shambhavi Adhikari el 10 de Mzo. de 2021
This is the error i have when i convert to table.

Iniciar sesión para comentar.


ANKUR KUMAR
ANKUR KUMAR el 10 de Mzo. de 2021
"Is there a way to have both field and values on the cell array?"
Let us create a sample structure
S.x = linspace(0,4*pi);
S.y = cos(S.x);
You can use fieldnames and struct2cell to extract the values:
name=fieldnames(S);
value=struct2cell(S);

Jorg Woehl
Jorg Woehl el 10 de Mzo. de 2021
Editada: Jorg Woehl el 11 de Mzo. de 2021
Shambhavi, you can use fieldnames to extract the fieldnames from your structure and add it to the end of your new cell array. For example, taking this 1-by-2 structure array from the MATLAB documentation:
% sample structure
field1 = 'f1'; value1 = zeros(1,10);
field2 = 'f2'; value2 = {'a', 'b'};
field3 = 'f3'; value3 = {pi, pi.^2};
field4 = 'f4'; value4 = {'fourth'};
s = struct(field1,value1,field2,value2,field3,value3,field4,value4);
% write data from structure to cell array
sCell = struct2cell(s);
% add fieldnames to cell array
sCell(:,:,end+1) = fieldnames(s);
sCell(:,:,1) to sCell(:,:,end-1) now contain your data, while sCell(:,:,end) contains your fieldnames.
If you prefer to have the fieldnames listed first, in sCell(:,:,1), followed by your data in sCell(:,:,2) to sCell(:,:,end), issue the following command after the above:
sCell = circshift(sCell,1,3);

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