Search code examples
matlabnested-loops

Loading and saving Mat file in a nested loop in Matlab


I want to load and save inside a nested loop in Matlab using "increasing" names, e.g.

for j=1:J
   for m=1:M
      load Bmj.mat
      ... A=...
      save A as Amj.mat
   end
end

Any suggestion?


Solution

  • You can use sprintf to format strings

    for ii=1:J
        for m=1:M
            suffix = sprintf( '%d%d.mat', ii, m );
            load( ['B', suffix] );
            % process...
            save( ['A', suffix], 'A' );
        end
    end
    

    PS,
    It is best not to use i as a variable name in Matlab.