Home > Mobile >  Changing folder and file name in a double Matlab loop
Changing folder and file name in a double Matlab loop

Time:09-17

I have a double for loop in Matlab. The first loop determines the working directory. The second loop determines the name of the file in the working directory that I want to load and work with:

for j=1:J

    cd / users/M_%j/    %************

    A_temp=cell(I,1);
    for ii=1:I
        if isfile(['A.' num2str(ii) '.mat'])
        load(['A.' num2str(ii) '.mat']);
        A_temp{ii}= A;
        end
    end


    A_final_x%j= vertcat(A_temp{:});         %************

    cd /users/

    save('A_final_x%j.mat', 'A_final_x%j')   %************
end

I don't know how to correctly replace the %j that you see in the three lines of my code highlighted by %************. Could you advise on how to proceed?

CodePudding user response:

I'm turning my comment into an answer... please see the code comments below which address why I've changed your code at each step

for j = 1:J
    % Create the file path
    fp = ['/users/M_', num2str(j)]; % Alternative: fp = sprintf('/users/M_%d', j );
    
    A_temp=cell(I,1);
    for ii = 1:I
        % Create a full path reference to the mat file
        filepath = fullfile( fp, ['A.' num2str(ii) '.mat'] );
        if exist( filepath, 'file' ) % exist is more flexible than "isfile"
            % Directly assign to a variable, will error if "A" isn't in the mat file
            % which is more robust than not knowing if you had a bad file
            A = getfield( load( filepath ), 'A' ); 
            A_temp{ii}= A;
        end
    end

    A_final_x = vertcat(A_temp{:}); % No need for a dynamic variable name

    % Define the output path
    outpath = fullfile( fp, ['A_final_x' num2str(j) '.mat'] );
    save( outpath, 'A_final_x' ); % save using the full path and a fixed var name
end
  • Related