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

8 ビュー (過去 30 日間)
Kevin Burg
Kevin Burg 2021 年 7 月 25 日
編集済み: Stephen23 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 件のコメント
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 Center および File ExchangeSearch Path についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by