8

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 can I make such a 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 without using cell2struct or for loop indexing? Can one use deal or similar?

4
  • Please notice that array to array non-for-loop assigment works nicely as in here stackoverflow.com/questions/8372619/… Commented Feb 7, 2012 at 22:22
  • 1
    It's probably poor form to tell people trying to help you to "please spare the "best-practice" hinting or similar "hand-waving"." Condescension is rarely considered an incentive for people to take time out of their day to try to help you. Commented Feb 8, 2012 at 9:39
  • 1
    I apologize if that seems to be rude, but it is a technical question and the answer I got is very much to the point! Unfortunately, there are members in the community that like to make unnecessary comments ;-) or remarks like "wow, i would not do that if i were you..", "consider using use oop" and similar non-related nonsense. I have a technical question. My point is if you don't know the answer please think of restricting yourself saying just something and spare the time of other users that would read this knowledge base in search of a solution. Commented Feb 8, 2012 at 12:25
  • Hint: Matlab2014 offers a new promising datatype called table mathworks.ch/ch/help/matlab/ref/table.html Somewhat into the direction of R's dataframes and python pandas. Commented Apr 3, 2014 at 14:09

2 Answers 2

10

You can use cell2mat :

cell2mat(phone_record)

ans =

1x2 struct array with fields:

name
phone

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks -- you just saved me a serious amount of work.
1

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 identity @(x) x, of course.

1 Comment

What is "the idendity"? Do you mean "the identity"? Independent of that, what is meant by it? Perhaps expand the answer a little bit to make it clear, if nothing else by adding a reference?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.