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?
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.
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.
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.
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 .
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
try with using importdata
function
A = importdata(`filename.txt`);
It will solve your question.
EDIT
Alternative 1)
A = dlmread('test_so.txt',',');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With