Matlab: howto convert an array of structure cells into an array of structures using a colon operator?

Assume that the array of cells is initialized with the following structure values.

% Phone book phone_record{1} = struct('name', 'Bob', 'phone', '1233323'); phone_record{2} = struct('name', 'Mike', 'phone', '3245524'); % How to make such or similar one-liner work? % phonebook(:) = phone_record{:} % Expected: % phonebook(1).name = 'Bob'; % phonebook(1).phone= '1233323'; % phonebook(2).name = 'Mike'; % phonebook(2).phone = '3245524'; 

Is it really possible to accomplish this without using cell2struct or for-loop indexing? Can I use a deal or the like?

Note: if you donโ€™t know the solution, please recommend a โ€œbestโ€ hint or similar โ€œmanual waveโ€.

+6
source share
2 answers

You can use cell2mat :

 cell2mat(phone_record) 

ans =

1x2 struct array with fields:

name
telephone

+7
source

Well,

 phone_book = cat( 2, phone_record{ :}) 

really uses the colon operator and will give the same result as cell2mat (phone_record).

Another non-colon solution is

 cellfun(@(x) x, phone_record).' 

in order to transform structures on the fly, for example, adding (missing) fields. Here we use identification, of course.

+1
source

Source: https://habr.com/ru/post/907885/


All Articles