我试图在循环中分配结构的字段值。
具有空值的结构声明:
result_struct = struct('a',{},'b',{},'c',{},'d',{})我在循环中赋值如下:
% assume a, b, c, d are variables in my workspace % field names match with the variable names for index=1:n % some computation and store results in variables (a-d) result_struct(index).a = a; result_struct(index).b = b; result_struct(index).c = c; result_struct(index).d = d; end我如何使用另一个循环将值赋给字段? 像那样:
for fname = fieldnames(result_struct)' result_struct(index).fname = fname; % field names and variable names match endI am trying to assign the field values of structure in loop.
Structure declaration with empty values:
result_struct = struct('a',{},'b',{},'c',{},'d',{})I am assigning values in loop like that:
% assume a, b, c, d are variables in my workspace % field names match with the variable names for index=1:n % some computation and store results in variables (a-d) result_struct(index).a = a; result_struct(index).b = b; result_struct(index).c = c; result_struct(index).d = d; endHow can I assign the values to the fields using another loop? Like that:
for fname = fieldnames(result_struct)' result_struct(index).fname = fname; % field names and variable names match end最满意答案
您需要使用动态字段名称来分配给结构(左手侧)。 对于右侧可以使用eval但这很危险,所以最好将变量fname保存到文件中,然后再次使用动态字段名称作为struct将其重新装入struct然后再访问fname 。
names = fieldnames(result_struct); for k = 1:numel(names) % Save variable to a file save('tmp.mat', names{k}); % Load it back into a struct tmp = load('tmp.mat', names{k}); result_struct(index).(names{k}) = tmp.(names{k}); end或者,您可以使用save和load将整个事物转换为结构,而无需遍历字段。
fields = fieldnames(result_struct); % Save all relevant variables to a file save('tmp.mat', fields{:}); % Load it back into the result_struct result_struct(index) = orderfields(load('tmp.mat'), fields);You need to use dynamic field names to assign to the struct (the leff-hand side). For the right hand side you could use eval but that is dangerous, so it's better to save your variable fname to a file and then load it back in as a struct prior to accessing fname, again using dynamic field names.
names = fieldnames(result_struct); for k = 1:numel(names) % Save variable to a file save('tmp.mat', names{k}); % Load it back into a struct tmp = load('tmp.mat', names{k}); result_struct(index).(names{k}) = tmp.(names{k}); endAlternately, you can use the save and load to just transform the entire thing into a struct without having to loop through the fields.
fields = fieldnames(result_struct); % Save all relevant variables to a file save('tmp.mat', fields{:}); % Load it back into the result_struct result_struct(index) = orderfields(load('tmp.mat'), fields);更多推荐
发布评论