Error:Field and value input arguments must come in pairs

38 次查看(过去 30 天)
I have a code with a structure array a which is initialized as follows
if true
a=struct([]);
for i=1:(v_max+5)/5
a(i).v_low=0;
a(i).v_up=0;
a(i).t_cat=0;
a(i).idlecat_p=0;
%Assign value to each field in the structure array.
end
end
Now I'm trying to make another structure array b with same fields as of a
if true
f=fieldnames(a);
b=struct(f{:},0);
end
Till now I didn't have the field idlecat_p but soon as I added that to a, I'm getting the following error:
if true
Error using struct
Field and value input arguments must come in pairs.
Error in Code (line 373)
b=struct(f{:},0);
end
It's like whenever I'm adding a new field to a, the above error is coming at the same line

采纳的回答

Walter Roberson
Walter Roberson 2018-7-11
Remember that when f is a cell array that struct(f{:},0) is the same as writing
struct(f{1}, f{2}, f{3}, f{4}, ... f{end}, 0)
which tells struct to use f{1} as a fieldname and give it the value f{2}, and to use f{3} as a fieldname and to give it the value f{4}, and so on, eventually taking the last field name and giving it a value of 0.
This can only work if you had an odd number of field names, so that the odd ones all get paired up with the following even one, except that the last odd one gets paired up with the 0 you provided.
cell2struct( repmat({0}, 1, length(f)), f, 2)

更多回答(1 个)

NALLARASU KRISH
NALLARASU KRISH 2022-12-23
When you create or modify struct in Matlab, you may ensure that the number of fields be in even number.

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by