How do I obtain size data from multi loaded text files?
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I'm loading up a pair of text files (from the working directory) containing numerical data with the following code;
files = dir('*.txt');
for i=1:length(files)
eval(['load ' files(i).name ' -ascii']);
end
Is there a way to obtain the size dimensions (for each text file) using this approach within the for loop?
0 Kommentare
Akzeptierte Antwort
dpb
am 10 Jun. 2014
Bearbeitet: dpb
am 11 Jun. 2014
Well, I misspoke on eval; to use the command-line form the filename can't be in a variable so that's the only way to do it.
What you really likely ought to do is switch over to using the functional form for load and also assign the result to a variable so you know the name.
The problem is that when you use the default assignment as done here, load "poofs" the variable name from the file name base name into the workplace(). That's ok for interactive use but difficult to handle easily programmatically in a script or function as then the only way to get access to that variable is either thru *eval or, perhaps a named structure field.
The latter would be something like...
[~,fn]=fileparts(files(i).name); % get the base name from the file name
s.(fn)=load(files(i).name,'-ascii'); % load a structure w/ field that name
[nr,nc]=size(s.(fn)); % and find out how big 'tis
Other than that you're at the mercy of eval and that's no road down which to travel..
See the documentation on structures in the 'Data Types' section for more details on using the dynamic name fields. Basically, the deal is if enclose a field name in paren's, that causes the variable to be evaluated and the value thereof to be used as the field name. Same idea as building a string for eval but much less error-prone.
() Even that isn't strictly true always, depending on the file name. There are a bunch of exceptions for filenames that include numerics or other special symbols so that you can't always get the imported variable name at all easily programmatically. See the doc for *load for details, but it isn't pretty...
Weitere Antworten (1)
dpb
am 10 Jun. 2014
Bearbeitet: dpb
am 10 Jun. 2014
files = dir('*.txt');
for i=1:length(files)
eval(['load ' files(i).name ' -ascii']);
No need for eval here, just write
load file(i).name '-ascii';
As to the question, depends on what you mean by size as to how.
files(i).bytes
contains the disk storage of the file, the size function returns the size of the arrays in Matlab storage. There's also
doc whos % not optional parameters for various uses
I don't understand the question title of "multi-loaded" text files?
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!