Create a struct from two cell arrays

25 次查看(过去 30 天)
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