Remove all fields from a struct except if

7 views (last 30 days)
Hi,
I have a struct mk with fields mk.id, mk.x and mx.z. There are 800 of each, so I have mk(1).id, ..., mk(800).id, and the same for x and z.
I need to do several calculations that require loading only one of these at the time, for a given parameter. This is, I have a function that takes one argument, say i, and I would like to load the fields that correspond to that i. Something such as load('input','mk(i)'), to get mk(i).id, mk(i).x and mk(i).z. This doesn't work, and load(fullfile('input.mat),'mk(i)') doesn't work either (with i replaced by a number). I receive a message saying "Warning: Variable 'mk(1)' not found".
Any suggestions? An alternative would be to load everything and delete all but mk(i).id, mk(i).x and mk(i).z, but I have no idea how to remove all but those fields.
Thanks,
Fernando

Accepted Answer

per isakson
per isakson on 17 Jul 2012
Edited: per isakson on 17 Jul 2012
MATFILE is the closest there is to your requirement. And it is a rather new feature. I use R20012a.
N = 8;
mk = struct( 'id' , num2cell(transpose(1:N)) ...
, 'x' , num2cell(rand(N,1)) ...
, 'y' , num2cell(randn(N,1)) );
save( 'mk.mat', 'mk' )
mo = matfile( 'mk.mat' ); % creates an object
mo.mk(7,1)
ans =
id: 7
x: 0.8407
y: 0.4882
.
However, there are problems with MATFILE, see: Writing to matfile in a loop

More Answers (0)

Categories

Find more on Structures 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!