How can I change all fields in a structure except one?
14 views (last 30 days)
Show older comments
Hi!
I've got a structure with 17 fields and 68 values for each of them (so a 1x68 struct with 17 fields). Since some of the 68 values don't have information, I would like to fill them by copying the information of another value (which has information) which I can do simply like this:
mystruct(67) = mystruct(65);
But this copies all the fields of the 65th value of the structure into the fields of the 67th value of the structure, and I would like to keep the first field of the 67th value of the structure intact (because it's the name field). Any idea how I can do this?
Thanks very much in advance.
0 Comments
Accepted Answer
Dave B
on 1 Nov 2021
Edited: Dave B
on 1 Nov 2021
You could iterate over the fields and copy them each one at a time unless they were the field you wanted to preserve, but I wouldn't recommend that for this case. Instead, how about just storing the name temporarily and setting it back again after?
cachename = mystruct(67).name; % or whatever it's called
mystruct(67) = mystruct(65);
mystruct(67).name = cachename;
You could even put that into a little function if you liked:
function s=copyallbutname(s,from,to)
n=s.name;
s(to)=s(from);
s(to).name=n;
end
If you want to iterate over names, you can do it like this:
fn = fieldnames(mystruct)
% Note I'm starting with 2 because you said you don't want the first field
% but I'd recommend using names not order if it's a struct!
for i = 2:numel(fn)
% can check fn{i}=="somename"
% or ismember(fn{i},listoffieldstokeep)
% etc.
% To use fn{i}:
mystruct(67).(fn{i}) = mystruct(65).(fn{i});
end
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!