Matlab fopen, is it possible to have a numeric file name? - matlab

I have the following code:
ptol = [2, 4, 8, ...];
a = ptol(1)
fid = fopen( a,'r');
I need to open a file determined by which number is called from ptol, i.e. if ptol(1) = 2, then fopen should open file 2.
Currently I get the error "invalid filename". How do I fix this?
The following code is what I need to use to "load" the data in the files I'm struggling to open in to a matrix.
fileName = strcat(num2str(a),'.ext');
file = fopen(fileName,'r');
count = 1;
lines2skip = 4;
mat = zeros(29,872);
while ~feof(file)
if count <= lines2skip
count = count+1;
[~] = fgets(file); % throw away unwanted line
continue;
else
line = strtrim(fgets(file));
mat = [mat ;cell2mat(textscan(line, '%f')).'];
count = count +1;
end
end

a is a number, I guess.
Thus, you need to specify a string which corresponds to the file name.
Does the file have any extension? num2str and strcat should do the magic.
The code:
fileName = strcat(num2str(a),'.ext');
fid = fopen(fileName,'r');
Notice that .ext has to be replace with the actual extension. If you are using .txt files, then replace with .txt.
Also, check for the position of the file (you need to specify the exact path).

Related

Read data to matlab with for loop

I want to read the data of a file with size about 60 MB into matlab in some variables, but I get errors. This is my code:
clear all ;
clc ;
% Reading Input File
Dataz = importdata('leak0.lis');
%Dataz = load('leak0.lis');
for k = 1:1370
foundPosition = 1 ;
for i=1:size(Dataz,1)
strp = sprintf('I%dz=',k);
fprintf(strp);
findValue = strfind(Dataz{i}, strp) ;
if ~isempty(findValue)
eval_param = strp + '(foundPosition) = sscanf(Dataz{i},''%*c%*c%*f%*c%*c%f'') ;';
disp(eval_param);
% str(foundPosition) = sscanf(Dataz{i},'%*c%*c%*f%*c%*c%f') ;
eval(eval_param);
foundPosition = foundPosition + 1 ;
end
end
end
When I debugged it, I found out that the dataz is empty & so it doesn't proceed to next lines. I replace it with fopen, load & etc, but it didn't work.
From the Matlab help files, import data is likely failing because it doesn't understand your file format.
From the help files
Name and extension of the file to import, specified as a string. If importdata recognizes the file extension, it calls the MATLAB helper function designed to import the associated file format (such as load for MAT-files or xlsread for spreadsheets). Otherwise, importdata interprets the file as a delimited ASCII file.
For ASCII files and spreadsheets, importdata expects to find numeric
data in a rectangular form (that is, like a matrix). Text headers can
appear above or to the left of the numeric data, as follows:
Assuming that your .lis files actually have delimited text.
You should adjust the delimiter in the importdata call so that Matlab can understand your file.
filename = 'myfile01.txt';
delimiterIn = ' ';
headerlinesIn = 1;
A = importdata(filename,delimiterIn,headerlinesIn);

Loading multiple text files from a single directory in matlab

First time here so please be gentle
So the basic idea is i have folders with just txt files that has about 20000 points each. I only want specific intervals from each of them.
I have a made a single file with the ranges for that looks like this
. 2715 2955
1132 1372
each row representing the range i want in one file
I want to batch load all the files and export the just the ranges of each. Ive lost too much sleep over this please help
dirName = '*'; %# folder path
files = dir( fullfile(dirName,'*.txt') ); %# list all *.xyz files
files = {files.name}' ; %'# file names
data = cell(numel(files),1) ; %# store file contents
for u=1:numel(files)
A=files{u} ; %# full path to file
files{u};
STR1 = A
B=load(STR1);
end
This is all i have come up with in 2 days. im new to matlab
Thanks
A very good help is the matlab help of fscanf, http://www.mathworks.co.uk/help/matlab/ref/fscanf.html. Also, in your load you don't have the path. Replace the last two lines in your for loop with:
STR1 = [dirName A]
fileID = fopen(STR1,'r');
formatSpec = '%f';
B = fscanf(fileID,formatSpec)
Or try:
delim = ' ';
nrhdr = 0;
STR1 = [dirName A]
A = importdata(STR1, delim, nrhdr);
A.data will be your data, I'm assuming no header lines.

Extract value MATLAB

I need to extract the first value of the following code:
3.43099,70.8539,91.701,FAIL
The file has the '.sol' extension, but it can be read in notepad or Matlab.
I just want to know how to to read in all *.sol files in a folder and how to write the extracted value in a text file.
Thanks a lot, i would be grateful.
NEW
ita='"';
for i=1:size(z,2)
word_to_replace=input('Replace? ','s');
tik=input('Replacement? ','s');
coluna=input('Column? ');
files = dir('*.txt');
for i = 1:numel(files)
if ~files(i).isdir % make sure it is not a directory
contents = fileread(files(i).name);
fh = fopen(files(i).name,'w');
val=num2str(z(i,coluna));
word_replacement=strcat(tik,val,ita);
contents = regexprep(contents,'word_to_replace','word_replacement');
fprintf(fh,contents); % write "replaced" string to file
fclose(fh) % close out file
end
end
end
Many thanks
File extension does not make a difference as to what MATLAB can "read", use the fileread command to load in the file and parse its contents. You can then split on commas, since it looks like it is comma separated
files = dir('*.sol');
fh = fopen('outFile.txt','w');
for i = 1:numel(files)
if ~files(i).isdir % make sure it is not a directory
contents = fileread(files(i).name);
parts = regexp(contents,',','Split');
fprintf(fh,[parts{1},'\n']);
end
end
fclose(fh)
This should do what you want. It will find all files in the current directory with the .sol extension, loop through all of them, grab the first value, and write it out to a text file.
Find and replace
Finding and replacing is relatively simple as well. You can do the same looping, read the file contents, run a replacement, and then rewrite that out to the same file.
files = dir('*.sol');
for i = 1:numel(files)
if ~files(i).isdir % make sure it is not a directory
contents = fileread(files(i).name);
fh = fopen(files(i).name,'w'); % open handle to same file just read for overwriting
contents = regexprep(contents,'toReplace','replacement'); % do string replacement
fprintf(fh,contents); % write "replaced" string to file
fclose(fh) % close out file
end
end

matlab How to remove .jpg from file name

I am looping through a lot of files and I need to remove the '.jpg' from each name.
Example file name:
20403y.jpg
but I just need the
20403y
All the file names end with 'y' if that helps.
One way is with regular expressions:
filename = 'myfilename.jpg';
pattern = '.jpg';
replacement = '';
regexprep(filename,pattern,replacement)
Result:
ans =
myfilename
If you have the filenames in a cell array feed the cell array to regexprep. As the documentation explains, "If str is a cell array of strings, then the regexprep return value s is always a cell array of strings having the same dimensions as str."
Example:
myfilenames = {'myfilename.jpg' 'afilename.jpg' 'anotherfilename.jpg' };
newfilenames= regexprep(myfilenames,'.jpg','');
Result:
newfilenames =
'myfilename' 'afilename' 'anotherfilename'
files = dir('*y.jpg');
% Loop through each
for id = 1:length(files)
% Get the file name (minus the extension)
[p, f] = fileparts(files(id).name); % f will just give you file name
% Use following to rename the files
% I think you don't want to rename them
% movefile(files(id).name, f);
end

How do you get the size of a file in MATLAB?

What is the best way to figure out the size of a file using MATLAB? The first thought that comes to mind is size(fread(fid)).
Please see the dir function as stated above.
Please note that the dir function works on files and not on directories only.
>> s = dir('c:\try.c')
s =
name: 'try.c'
date: '01-Feb-2008 10:45:43'
bytes: 20
isdir: 0
datenum: 7.3344e+005
You can use the DIR function to get directory information, which includes the sizes of the files in that directory. For example:
dirInfo = dir(dirName); %# Where dirName is the directory name where the
%# file is located
index = strcmp({dirInfo.name},fileName); %# Where fileName is the name of
%# the file.
fileSize = dirInfo(index).bytes; %# The size of the file, in bytes
Or, since you are looking for only one file, you can do what Elazar said and just pass an absolute or relative path to your file to DIR:
fileInfo = dir('I:\kpe\matlab\temp.m');
fileSize = fileInfo.bytes;
Use the fact that MatLab has access to Java Objects:
myFile = java.io.File('filename_here')
flen = length(myFile)
If you don't want to hardcode in your directory, you can use the built in pwd tool to find the current directory and then add your file name to it. See example below:
FileInfo = dir([pwd,'\tempfile.dat'])
FileSize = FileInfo.bytes
The question seems to indicate that fopen/fread/.. is used. In this case, why not seeking to the end of the file and reading the position?
Example:
function file_length = get_file_length(fid)
% extracts file length in bytes from a file opened by fopen
% fid is file handle returned from fopen
% store current seek
current_seek = ftell(fid);
% move to end
fseek(fid, 0, 1);
% read end position
file_length = ftell(fid);
% move to previous position
fseek(fid, current_seek, -1);
end
Matlab could have provided a shortcut..
More on ftell can be found here.
This code works for any file and directory (no need for absolute path) :
dirInfo=dir(pwd);
index = strcmp({dirInfo.name},[filename, '.ext']); % change the ext to proper extension
fileSize = dirInfo(index).bytes
Easy way to find size of file is:
enter these cammands
K=imfinfo('filename.formate');
size_of_file=K.FileSize
and get size of file.