matlab - unsure of fullfile command syntax for path location -
here's piece of code i'm working on, based on example previous comment. in first line, make path? extend way macintosh hd/users/..../documents/matlab (matlab folder in path ascii files i'm analyzing stored) or start @ point? i'm not sure replace 'path', 'to', 'folder' in below example. i'm more confused because current dir showing in matlab window correct 1 files i'm working stored. in case, do fullfile line? i'm trying display contents of newly truncated files. how do that? thanks!
folder = fullfile('path', 'to', 'folder'); f = dir(fullfile(folder, '*.asc')); matrices = struct(); ii = 1 : numel(f) name = fullfile(folder, f(ii).name); o = dlmread(name); matrices.(f(ii).name) = o(1:80,:); end
as documentation says, fullfile
allows construct filename it's parts without having worry whether use / or \ file separators , without doing things messy way of old
filename = ['path' filesep 'to' filesep 'files'];
or worse!
folder = '/path/to/file';
you'll run sorts of issues if attempt switch between operating systems.
in example have provided
folder = fullfile('users', 'documents', 'matlab')
side note: please don't store data in folder
you correct if files you're trying load in current directory, don't need folder
variable because if type dlmread(filename)
work.
the issue though, is requires user in specific directory run code , may not clear user folder is. code have provided more robust because doesn't depend on current directory. in mind best practice never rely on current directory. nothing worse in mind seeing change directories within matlab can access data!
so keeping in mind fullfile
does, i'll annotate code below
folder = fullfile('path', 'to', 'folder');
stores path data lives. can either absolute path (as you've stated in question) '/users/blah/data'
or path relative current directory 'data'
if data lives in fullfile(pwd, 'data')
. former preferred method.
f = dir(fullfile(folder, '*.asc'));
this calls dir
on looking files/folders .asc
extension in folder.
name = fullfile(folder, f(ii).name);
this line constructs absolute path file of interest since dir
returns filename, not folder lives in (one of biggest annoyances).
o = dlmread(name);
then reads actual file using full path provided.
again, real benefit here don't have in specific directory execute code.
so answer question directly, know of this. if data lives in current directory could set folder
current directory
folder = pwd;
or if want kind others , future self can specify absolute path (preferably passed function argument , not hard-coded)
function matrices = getfiles(folder) f = dir(fullfile(folder, '*.asc')); matrices = struct(); ii = 1 : numel(f) name = fullfile(folder, f(ii).name); o = dlmread(name); matrices.(f(ii).name) = o(1:80,:); end end matrices = getfiles(fullfile('user', 'defined', 'path', 'to', 'data'));
Comments
Post a Comment