Matlab循环:从目录加载东西时忽略变量定义

时间:2016-04-15 14:44:18

标签: matlab loops variables

我是MATLAB的新手并尝试在循环中运行循环。我事先定义了变量ID,例如ID={'100'}。在我的循环中,然后我想转到ID的目录,然后在那里加载matfile。但是,每当我加载matfile时,突然ID定义被所有可能的ID(目录中ID 100所有的所有文件夹)覆盖。这是我的代码 - 我也试过fullfile,但到目前为止没有运气:

ID={'100'}

for subno=1:length(ID)     % first loop
  try         
   for sessno=1:length(Session) %  second loop, for each ID there are two sessions   
    subj_name =  ([ID{subno} '_' Session{sessno} '_vectors_SC.mat']);
    cd(['C:\' ID{subno} '\' Session{sessno}]);
    load(subj_vec_name) % the problem occurs here, when loading, not before
    end
  end
end

当我检查ID的长度时,它现在不是1(一个ID,即100),但是目录中的所有可能的ID也是100,并且循环再次针对所有其他可能的ID进行迭代(虽然它应该在ID 100之后停止。)

2 个答案:

答案 0 :(得分:5)

You should always specify an output to load to prevent over-writing variables in your workspaces and polluting your workspace with all of the contents of the file. There is an extensive discussion of some of the strange potential side-effects of not doing this here.

Chances are, you have a variable named ID inside of the .mat file and it over-writes the ID variable in your workspace. This can be avoided using the output of load.

The output to load will contain a struct which can be used to access your data.

data = load(subj_vec_name);

%// Access variables from file
id_from_file = data.ID;

%// Can still access ID from your workspace!
ID

Side Note

It is generally not ideal to change directories to access data. This is because if a user runs your script, they may start in a directory they want to be in but when your program returns, it dumps them somewhere unexpected.

Instead, you can use fullfile to construct a path to the file and not have to change folders. This also allows your code to work on both *nix and Windows systems.

subj_name =  ([ID{subno} '_' Session{sessno} '_vectors_SC.mat']);

%// Construct the file path
filepath = fullfile('C:', ID{subno}, Session{sessno}, subj_name);

%// Load the data without changing directories
data = load(filepath);

答案 1 :(得分:1)

With the command load(subj_vec_name) you are loading the complete mat file located there. If this mat file contains the variable "ID" it will overwrite your initial ID. This should not cause your outer for-loop to execute more than once. The vector 1:length(ID) is created by the initial for-loop and should not get overwritten by subsequent changes to length(ID).

If you insert disp(ID) before and after the load command and post the output it might be easier to help.

相关问题