Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: howto convert cell array of structs into struct array using colon operator?

Tags:

matlab

Assume there is a cell array initialized with the following struct 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 indeed possible to accomplish this w/o using cell2struct or for-loop indexing? Can one use deal or similar?

Note: if you don't know the solution please spare the "best-practice" hinting or similar "hand-waving".

like image 341
Yauhen Yakimovich Avatar asked Feb 07 '12 22:02

Yauhen Yakimovich


2 Answers

You can use cell2mat :

cell2mat(phone_record)

ans =

1x2 struct array with fields:

name
phone

like image 179
Andrey Rubshtein Avatar answered Sep 30 '22 15:09

Andrey Rubshtein


Well,

phone_book = cat( 2, phone_record{ :})

does indeed use the colon operator, and will give the same result as cell2mat(phone_record).

Another non-colon solution is

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

with the benefit of transforming the structs on the fly, for example adding (missing) fields. Here we use the idendity, of course.

like image 38
Wolfgang Kuehn Avatar answered Sep 30 '22 16:09

Wolfgang Kuehn