Using a loop to read a .mat file, extract a certain variable, and add to a matrix without overwriting

8 次查看(过去 30 天)
I am trying to extract a certain variable from 36 total directories, all with a similar .mat file name (plotvars.mat). Inside this .mat file, there is a variable called plotvars.al that I am trying to extract. I want the value from the 5th row last colum (5,end). I then want to add this value to a matrix. However, whenever I do this I keep overwriting the previous value so it ends up being the variable from the 36th file repeated. How do I prevent overwriting the value in my matrix?
I believe the problem lies in the line below. I do not know how to specify that plotvars.al(5,end) needs to be extracted from directory 1:36, and then added to the corresponding row in column 2
compare(ind,:) = [bs_data(ind,3),plotvars.al(5,end)];
Below is my full code
global ind bs_data fullFileName
load('bs_data.mat', 'bs_data');
addpath('C:\Users\me\Project\Source');
folder = 'C:\Users\me\Project\BS';
addpath(folder);
compare = zeros(36,2);
for ind=1:36
betdir = fullfile(sprintf('./plotvars_%d', ind));
mkdir(betdir);
addpath(betdir);
cd(folder);
for ind=1:36
cd(betdir);
load plotvars;
compare(ind,:) = [bs_data(ind,3),plotvars.al(5,end)]; % This is where I am having the problem
cd(folder);
end
end
  1 个评论
Stephen23
Stephen23 2021-7-26
编辑:Stephen23 2021-7-26
Your code could easily be much more robust:
  • Do NOT load directly into the workspace, load into an output variable instead (which is a scalar structure).
  • Do NOT use CD to import/export data files, use absolute/relative filenames (generated using FULLFILE).
  • Avoid GLOBAL variables.

请先登录,再进行评论。

回答(1 个)

Sruthi Gundeti
Sruthi Gundeti 2021-7-26
Hi Kevin ,
Use same for loop for changing directory , load plotvars and update compare
using different for loops making the loading and updating from the same file for over 36 times hence resulting the variable from the 36th file repeated.
for ind=1:36
betdir = fullfile(sprintf('./plotvars_%d', ind));
mkdir(betdir);
addpath(betdir);
cd(folder);
cd(betdir);
load plotvars;
compare(ind,:) = [bs_data(ind,3),plotvars.al(5,end)]; % This is where I am having the problem
cd(folder);
end

类别

Help CenterFile Exchange 中查找有关 Search Path 的更多信息

产品


版本

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by