在双 Matlab 循环中更改文件夹和文件名
Changing folder and file name in a double Matlab loop
我在 Matlab 中有一个双 for
循环。第一个循环确定工作目录。第二个循环确定我要加载和使用的工作目录中的文件名:
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
我不知道如何正确替换您在我代码中用 %************
突出显示的三行代码中看到的 %j
。你能建议如何进行吗?
我正在将我的 变成一个答案...请参阅下面的代码注释,其中说明了为什么我在每一步都更改了您的代码
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
我在 Matlab 中有一个双 for
循环。第一个循环确定工作目录。第二个循环确定我要加载和使用的工作目录中的文件名:
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
我不知道如何正确替换您在我代码中用 %************
突出显示的三行代码中看到的 %j
。你能建议如何进行吗?
我正在将我的
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