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

2 views (last 30 days)
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!

Accepted Answer

Prateek Rai
Prateek Rai on 19 Jun 2020
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”.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!