Open multiple files in Matlab - matlab

I have multiple files that I want to open using fopen. The files have a similar pattern, I have tried to use a for loop as follows, but it does not work. Any ideas how to open each file. Thanks in advance.
for ii = 0:12
file = fprintf('population_%d.dat', ii); % -----> File names
generations_fid = fopen(file); % Question ???
matrix = {};
while ~feof(generations_fid)
generations = cell2mat(textscan(generations_fid, repmat('%f', 1, (3))));
if isempty(generations)
fgetl(generations_fid);
else
matrix{end+1} = generations;
end
end
end

You want to be using sprintf to dynamically generate the file name, not fprintf.
file = sprintf('population_%d.dat', ii);
It's also good practice to open your file with the required permissions. In your case, it looks like you're reading, so you should use
generations_fid = fopen(file, 'r');

Related

read multiple files in from a directoryusing matlab

How can read multiple files in from a directory using matlab? Can someone please help correct my code below:
files =dir(fullfile(directory_path,'*.dat'));
numfiles = length('*.dat');
mydat = cell(1, numfiles);
for k = 1:numfiles
mydata{k} = fopen([directory_path,files(k).name]);
values=textscan(mydata{k},'%s','delimiter','\n');
fclose(fid);
%fprintf(values)
....do something with values.....
end
.dat files are just many rows and single column of strings that need to be read in a loop and processed further.
Thanks
fopen gives file pointer, which you save to mydata{k}, and try to release by fclose(fid). There is no fid, so it doesn't work.
What you should do is replace mydata{k} with fid. And probably values by mydata{k}.
The other bug is in numfiles = .... You will always have numfiles = 5, as there are 5 characters in the '*.dat'.
numfiles = length(files);
would be better, although you would also count directories. Check one of the other questions how to solve this.
Thanks Zizy Archer.
I solved the problem this way:
files =dir(fullfile(directory_path,'*.dat'));
numfiles = length(files);
for k = 1:numfiles
textFileName = [directory_path,files(k).name]
fid = fopen(textFileName, 'r');
textData = textscan(fid,'%s','delimiter','\n');
fclose(fid);
data = textData{:,1}
end

How to read multiple jpg images in matlab [duplicate]

I have certain images in a directory and I want to load all those images to do some processing. I tried using the load function.
imagefiles = dir('F:\SIFT_Yantao\demo-data\*.jpg');
nfiles = length(imagefiles); % Number of files found
for i=1:nfiles
currentfilename=imagefiles(i).name;
I2 = imread(currentfilename);
[pathstr, name, ext] = fileparts(currentfilename);
textfilename = [name '.mat'];
fulltxtfilename = [pathstr textfilename];
load(fulltxtfilename);
descr2 = des2;
frames2 = loc2;
do_match(I1, descr1, frames1, I2, descr2, frames2) ;
end
I am getting an error as unable to read xyz.jpg no such file or directory found, where xyz is my first image in that directory.
I also want to load all formats of images from the directory instead of just jpg...how can i do that?
You can easily load multiple images with same type as follows:
function Seq = loadImages(imgPath, imgType)
%imgPath = 'path/to/images/folder/';
%imgType = '*.png'; % change based on image type
images = dir([imgPath imgType]);
N = length(images);
% check images
if( ~exist(imgPath, 'dir') || N<1 )
display('Directory not found or no matching images found.');
end
% preallocate cell
Seq{N,1} = []
for idx = 1:N
Seq{d} = imread([imgPath images(idx).name]);
end
end
I believe you want the imread function, not load. See the documentation.
The full path (inc. directory) is not held in imgfiles.name, just the file name, so it can't find the file because you haven't told it where to look. If you don't want to change directories, use fullfile again when reading the file.
You're also using the wrong function for reading the images - try imread.
Other notes: it's best not to use i for variables, and your loop is overwriting I2 at every step, so you will end up with only one image, not four.
You can use the imageSet object in the Computer Vision System Toolbox. It loads image file names from a given directory, and gives you the ability to read the images sequentially. It also gives you the option to recurse into subdirectories.

reading decimal number with GUI matlab

I am developing a user interface using matlab wich allows to browse and load a text file and display some curves. I am facing a problem, my file text is a set of decimal number, matlab is reading those number as two columns.
this is an exemple: u find here the file that I am working on:
After runing this code :
[filename pathname] = uigetfile({'*.txt'},'File Selector');
fullpathname = strcat(pathname,filename);
text = fileread(fullpathname); %reading information inside a file
set(handles.text6,'string',fullpathname)%showing full path name
set(handles.text7,'string',text)%showing information
loaddata = fullfile(pathname,filename);
xy = load(loaddata,'-ascii','%s');
t = xy(:,1);
i = xy(:,3);
handles.input1 = i;
handles.input2 = t;
axes(handles.axes1);
plot(handles.input1,handles.input2)
the curves looks so strenge, so I checked the result of xy= load(loaddata,'-ascii') using command window and here the problem appears!
So I have now 12 columns instead of 6 ! can u help me please?
I tried with strrep(data,',','.') but it doesnt work !
Since you are using commas, for your radix point, you will want to first load in the entire file as a string, replace the , with . and then you can use str2num to convert the entire file to a numeric array
% Read the entire file into memory
fid = fopen(loaddata, 'rb');
contents = fread(fid, '*char')';
fclose(fid);
% Replace `,` with `.`
contents = strrep(contents, ',', '.');
% Now convert to numbers
data = str2num(contents);

Multiple file reading

I have more than 10,000 csv file in one folder and file names are 0,1,2,3... like that. I would like to read them and write into one file for further processing.I tried this
files= dir('C:\result\*.csv');
outs = cell(numel(files),1)
for i = 1:numel(files)
out{i} = csvread('%i',2,0)
end
but it didn't work.
Rather than reading them in as csv files, I would just read in the raw files and write them out again. This will likely be much faster.
files = dir('C:\result\*.csv');
filenames = fullfile('C:\result', {files.name});
% Sort the files based on their number
[~, ind] = sort(str2double(regexp(filenames, '[0-9]+(?=\.csv$)', 'match', 'once')));
filenames = filenames(ind);
% Open the file that you want to combine them into
outfile = 'output.csv';
outfid = fopen(outfile, 'wb');
for k = 1:numel(filenames)
% Open each file
fid = fopen(filenames{k}, 'rb');
% Read in contents and remove any trailing newlines
contents = strtrim(fread(fid, '*char'));
% Write out the content and add a newline
fprintf(outfid, '%s\n', contents);
% Close the input file
fclose(fid);
end
fclose(outfid);

How to read numbered sequence of .dat files into MATLAB

I am trying to load a numbered sequence of ".dat" named in the form a01.dat, a02.dat... a51.dat into MATLAB. I used the eval() function with the code below.
%% To load each ".dat" file for the 51 attributes to an array.
a = dir('*.dat');
for i = 1:length(a)
eval(['load ' a(i).name ' -ascii']);
end
attributes = length(a);
I ran into problems with that as I could not easily manipulate the data loaded with the eval function. And I found out the community is strongly against using eval. I used the csvread() with the code below.
% Scan folder for number of ".dat" files
datfiles = dir('*.dat');
% Count Number of ".dat" files
numfiles = length(datfiles);
% Read files in to MATLAB
for i = 1:1:numfiles
A{i} = csvread(datfiles(i).name);
end
The csvread() works for me but it reads the files but messes up the order when it reads the files. It reads a01.dat first and then a10.dat and a11.dat and so on instead of a01.dat, a02.dat... The contents of each files are signed numbers. Some are comma-delimited and single column and this is an even split. So a01.dat's contents are comma-delimited and a02.dat's content are in a single column.
Please how do I handle this?
Your problem seems to be sorting of the files. Drawing on a question on mathworks, this should help you:
datfiles = dir('*.mat');
name = {datfiles.name};
[~, index] = sort(name);
name = name(index);
And then you can loop with just name:
% Read files in to MATLAB
for i = 1:1:numfiles
A{i} = csvread(name{i});
end