Clear Filters
Clear Filters

Error:Field and value input arguments must come in pairs

20 views (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 11 Jul 2018
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)

More Answers (1)

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

Categories

Find more on Structures in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!