Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read file in matlab?

I have a txt file, and the content of the file is rows of numbers, each row have 5 float number in it, with comma seperate between each number. example:

1.1 , 12 , 1.42562, 3.5 , 2.2

2.1 , 3.3 , 3 , 3.333, 6.75

How can I read the file content into matrix in matlab? So far I have this:

fid = fopen('file.txt');
comma  = char(',');
A = fscanf(fid, ['%f', comma]);
fclose(fid);

The problem is that it's only give me the first line and when I try to write the content of A I get this: 1.0e+004 * some number

Can someone help me please? I guess that for the file I need to read it in a loop but I don't know how.

Edit: One more question: When I do output to A I get this:

A =

1.0e+004 *
4.8631         0         0         0    0.0001
4.8638   -0.0000   -0.0000    0.0004    0.0114
4.8647   -0.0000   -0.0000    0.0008    0.0109

I want the same values that in the file to be in the matrix, how can I make the numbers to be regular float and not formatted like this? Or are the numbers in the matrix actually float, but the output is just displayed like this?

like image 204
shlomi Avatar asked Apr 23 '13 18:04

shlomi


People also ask

How do I read the contents of a file in MATLAB?

Use fopen to open the file, specify the character encoding, and obtain the fileID value. When you finish reading, close the file by calling fclose(fileID) . A = fscanf( fileID , formatSpec , sizeA ) reads file data into an array, A , with dimensions, sizeA , and positions the file pointer after the last value read.

How do I read a file from a directory in MATLAB?

Direct link to this commentS = dir(...); % all of the names are in the structure S anyway. N = {S.name}; % but if you really want a cell array of names, do this.

How do I load a text file into MATLAB?

Alternatively, right-click the name of the file in the Current Folder browser and select Import Data. Then, select the file you want to import. Using the Import Tool window, set the importing options and then click Import Selection to import the data into MATLAB.

How do I read a character file in MATLAB?

Description. text = fileread( filename ) returns contents of the file filename as a character vector. text = fileread( filename ,Encoding= encoding ) opens filename using the encoding specified by encoding .


2 Answers

MATLAB's built-in dlmread function would be a much easier solution for what you want to accomplish.

A = dlmread('filename.txt',',') % call dlmread and specify a comma as the delimiter
like image 167
Doresoom Avatar answered Oct 04 '22 03:10

Doresoom


try with using importdata function

A = importdata(`filename.txt`);

It will solve your question.

EDIT

Alternative 1)

A = dlmread('test_so.txt',',');
like image 41
fpe Avatar answered Oct 04 '22 02:10

fpe