How to load .mat data from another folder?

99 ビュー (過去 30 日間)
Susan
Susan 2021 年 8 月 16 日
編集済み: Susan 2021 年 8 月 17 日
Hey,
I have several mat files located in a folder called "matFile". the script is located in the uperfolder of this matFile folder. I mean Folder1 incluses the script and matFile folder. Using following lines I try to access to the mat files. Each mat file is a 1-by-190 cell array
matpath = 'C\...\matFile';
matfiles = dir(fullfile(matpath ,'*'));
N1 = setdiff({matfiles.name},{'.','..'});
then N1 give me all the data in matFile folder, i.e.,
{'time1.mat'} {'time2.mat'} {'time3.mat'} {'time4.mat'}
{'location1.mat'} {'location2.mat'} {'location3.mat'} {'location4.mat'}
{'space1.mat'} {'space2.mat'} {'space3.mat'} {'space4.mat'}
However, when I call load(N1{1}) I got the error that this file is not in the directory. Any idea? Is there a way that I can load data in a for loop?
Thanks in advance!
  3 件のコメント
VBBV
VBBV 2021 年 8 月 17 日
%if true
 matpath = 'C\...\matFile\';
matfiles = dir(fullfile(matpath ,'*.mat'));
N1 = setdiff({matfiles.name},{'.','..'});

Also do these changes

Susan
Susan 2021 年 8 月 17 日
Thank you!

サインインしてコメントする。

採用された回答

Kelly Kearney
Kelly Kearney 2021 年 8 月 17 日
The dir command returns the path to each file in the folder field, so you need to append that to recreate the full path names for your files:
N1 = fullfile(matfiles(1).folder, setdiff({matfiles.name},{'.','..'}));
Although in this case, seeing that you're only looking for .mat files, I suggest using a more specific filter and eliminating the setdiff call:
matfiles = dir(fullfile(matpath, '*.mat'));
N1 = fullfile({matfiles.folder}, {matfiles.name});

その他の回答 (1 件)

Jeff Miller
Jeff Miller 2021 年 8 月 17 日
You need the folder name at the beginning of the string you pass to load, maybe something like this:
for iFile = 1:numel(N1)
s = [matpath '\' N1{iFile}];
load(s);
end
  2 件のコメント
Stephen23
Stephen23 2021 年 8 月 17 日
編集済み: Stephen23 2021 年 8 月 17 日
It is recommended to use FULLFILE:
F = fullfile(matpath,N1{iFile});
and to load into an output variable:
S = load(F);
Susan
Susan 2021 年 8 月 17 日
編集済み: Susan 2021 年 8 月 17 日
Thanks for your response.
for iFile = 1:numel(N1)
F = fullfile(matpath,N1{iFile});
S{iFile} = load(F);
end
read through the first mat file to the fifth one and then gives and error that
Error using load
Cannot read file C:\...\matFile\location2.mat.
Any idea? However, I can load ('C:\...\matFile\location2.mat') but when it runs a for loop I get this error. I think its because of running out of memory. I tried "fopen('all')" which replys [].

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by