%Lets say I have a multi-element cell array with different variables/feilds within
c{1,1}.name = 'Tom'; c{1,1}.age = 48;
c{2,1}.name = 'Bob'; c{2,1}.age = 24;
c{3,1}.name = 'Jim'; c{3,1}.age = 12;
%I would like to create a vector, vec_age = [48 24 12]; from this data set
% without writing the loop
for i =1:length(c), vec_age(i) = c{i,1}.age; end
% Something nice would be similar to how you pull a vector from a matrix, v = m(:,3);
% in the form of vec_age = c{:,1}.age; ... but alas this does not work
% Thank you in advance for suggestion to a small problem that has been nagging me.

 채택된 답변

Walter Roberson
Walter Roberson 2022년 1월 24일

0 개 추천

c{1,1}.name = 'Tom'; c{1,1}.age = 48;
c{2,1}.name = 'Bob'; c{2,1}.age = 24;
c{3,1}.name = 'Jim'; c{3,1}.age = 12;
vec_age = cellfun(@(S) S.age, c)
vec_age = 3×1
48 24 12
This does not assume that the structs all have the same fields in the same order, which Benjamin's answer assumes.

댓글 수: 1

John
John 2022년 1월 24일
편집: John 2022년 1월 25일
I oversimplified my case as I was trying to be concise. The data set I have is not of my making and the data types within are disparate. This solution works well. Thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

릴리스

R2021b

태그

질문:

2022년 1월 24일

편집:

2022년 1월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by