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

22 views (last 30 days)
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 Comment
Stephen23
Stephen23 on 26 Jul 2021
Edited: Stephen23 on 26 Jul 2021
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.

Sign in to comment.

Answers (1)

Sruthi Gundeti
Sruthi Gundeti on 26 Jul 2021
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

Categories

Find more on Search Path in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!