MATLAB Answers

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

조회 수: 4(최근 30일)
Kevin Burg
Kevin Burg 2021년 7월 25일
편집: Stephen 2021년 7월 26일
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
Stephen
Stephen 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

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by