Sep 9, 2010

MatLab file reading writing

This is the latest:
-----------------------------
fh1 = fopen('/home/reza/work/depth_arsalan/kitti_argo/data_rendered/train.txt', 'w');
lines = textscan(fh1, '%s', 'delimiter', '\n');
lines = lines{1};
fclose(fh1);
totalImages = length(lines);


Reading:
--------
We can use fscanf.

sample_names_fid = fopen('sampleNames.txt', 'r');

number_of_samples = textscan(sample_names_fid, '%d', 1, 'delimiter', '\n');

size = number_of_samples{1}

We can read the file by other specifier. If we want to read the string in a file
file_name = textscan(sample_names_fid, '%s', 1, 'delimiter', '\n');

name = file_name{1}

c = str2mat(name);

reading until end of file:
data_1 = []; fid1 = fopen('file_name_3.txt');
name = textscan(fid1, '%s')
for k=1:size(name{1},1)
n = name{1}
fid = fopen(n{k}, 'r');
     j=0;
    while ~feof(fid)
         j = j + 1;
         temp = textscan(fid, '%f %f %f', 1, 'delimiter', ',');
         data_1 = [data_1; temp{1} temp{2} temp{3}];
     end
 fclose(fid);
end
fclose(fid1);

Writing:
--------
We can use dlmwrite or fprintf for writing a file in MatLab.
1. dlmwrite:
dlmwrite(file_name, data, delimiter);

2. fprintf:
fid = fopen('sample_file.txt','w');
fprintf(fid, '%8.6f', data);
fclose(fid);

A new file 'sample_file.txt' will be opened in writing mode.
It output will be formatted:
Field width 8
Precision 6
Fixed point notation
Notation of fprintf
Example of fprintf

Issue with reading file from a variable name
http://www.mathworks.com/matlabcentral/newsreader/view_thread/132738

No comments:

Down with the Dictatorship!

    "Let them hate me, so that they fear me" - Caligula 41AD