Create a struct from two cell arrays

조회 수: 21 (최근 30일)
Deepa Maheshvare
Deepa Maheshvare 2021년 8월 22일
편집: Awais Saeed 2021년 8월 22일
I've the following cell arrays
keys =
4×1 cell array
{'n' }
{'key12'}
{'key13'}
{'key14'}
values =
4×1 cell array
{[ 10]}
{[ 1]}
{[ 1]}
{'Hello'}
When I try to create a struct in the following manner
args=[names;values];
structure = struct(args{:})
the below error occurs
Error using struct
Field names must be non-empty character vectors or a string scalars.
Error in setting.load_setting (line 19)
structure = struct(args{:})
Could someone please have a look?

채택된 답변

Awais Saeed
Awais Saeed 2021년 8월 22일
keys = {'n', 'key12', 'key13','key14'};
values = {10, 1 1 , 'Hello'};
names = {'f1', 'f2', 'f3', 'f4'};
args=[names;values];
structure = struct(args{:})
Seems to work for me
  댓글 수: 1
Awais Saeed
Awais Saeed 2021년 8월 22일
편집: Awais Saeed 2021년 8월 22일
Perhaps you are trying with
names = {'f1', 'f2', '', ''};
This will cause problems. If you must proceed this way I think it would be better to replace those empty cells with some string
keys = {'n', 'key12', 'key13','key14'};
values = {10, 1 1 , 'Hello'};
names = {'f1', 'f2', '', ''};
% get locations of empty cell elements
idx = cellfun('isempty',names);
[row, col] = find(idx);
% replace those empty cells with some string
for jj = 1:1:size(col,2)
idx = col(jj);
names{idx} = ['skip' num2str(jj)];
end
% Now concatenate cells
args=[names;values]
% convert to struct
P = struct(args{:});
struct2table(P)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by