How to convert an array of cells into an array of structures?

조회 수: 1 (최근 30일)
Melina Lucia
Melina Lucia 2018년 1월 30일
답변: Prateek Rai 2020년 6월 19일
Hello, I want convert an array of cells into a an array of structures:
address1 = { 'aaa'; 'bbb'; 'ccc' }
address2 = { 'ddd'; 'eee'; 'fff' }
address3 = { 'ggg'; 'hhh'; 'iii' }
address4 = { 'jjj'; 'kkk'; 'lll' }
address5 = { 'mmm'; 'nnn'; 'ooo' }
addresses = {address1; address2; address3; address4; address5}
colHeadings = { 'name'; 'address'; 'city'}
addressStruct = cell2struct(addresses, colHeadings, 2)
But this does not work, I got the following error:
addresses =
5×1 cell array
{3×1 cell}
{3×1 cell}
{3×1 cell}
{3×1 cell}
{3×1 cell}
colHeadings =
3×1 cell array
{'name' }
{'adress'}
{'city' }
Error using cell2struct
Number of field names must match number of fields in new structure.
Error in e4 (line 11)
addressStruct = cell2struct(adresses, colHeadings, 1)
May be the problem is, that a single address is a vertikal array 3*1. How can I do this in right way?
Thank you very much for help!

채택된 답변

Prateek Rai
Prateek Rai 2020년 6월 19일
As per my understanding you are trying to convert an array of cells into an array of structures but "cell2struct" is throwing an error. I think the Issue is with the way of concatenating all addresses in “addresses”. Use vertcat instead to concatenate the cell arrays.
Here is the sample code :
address1 = { 'aaa' 'bbb' 'ccc' }
address2 = { 'ddd' 'eee' 'fff' }
address3 = { 'ggg' 'hhh' 'iii' }
address4 = { 'jjj' 'kkk' 'lll' }
address5 = { 'mmm' 'nnn' 'ooo' }
addresses = vertcat(address1, address2, address3, address4, address5)
colHeadings = { 'name'; 'address'; 'city'}
addressStruct = cell2struct(addresses, colHeadings, 2)
You can refer to the following documentation for more information on “vertcat”.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Time Series Objects에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by