Navdeep Goel
Navdeep Goel

Reputation: 1

How to use Struct in mat files in a for loop in MATLAB?

Thanks to all in advance. I am trying to execute the following code in MATLAB and getting accurate results. But when i try this to execute in a for loop, i don't want to write nim_10_boat in the last line of the for loop. I want it should be dynamically placed. Please suggest.

`for filenames = {'nim_01_boat', 'nim_10_boat'}
thisfile = filenames{2};
datastruct = load(thisfile);
xyz = datastruct.**nim_10_boat**;
end`

when i execute datastruct in the command window datastruct =

         im: [256x256 uint8]
          n: 0.1000
          K: 1
        win: 3
nim_10_boat: [256x256 uint8]

Upvotes: 0

Views: 41

Answers (1)

kedarps
kedarps

Reputation: 861

You can dynamically access field names as follows:

% a sample struct
S = struct('a', randn(3), 'b', randn(5), 'c', randn(7));
fieldNames = {'a', 'b', 'c'};

for f = 1:length(fieldNames)
   % access field
   thisField = S.(fieldNames{f});
end

Note the use of () to access field names using variable names.

Upvotes: 2

Related Questions