user2468702
user2468702

Reputation: 141

Reading from a text file in matlab

I have data of the following format in "file.txt":

b0,  2,1
b1,  3,4
b2,  5,6
b3,  7,8
b4,  9,10
L0, 11, 12
L1, 13, -154
L2, 16, 18
L3,-19,-20
L4,-21,-22
L5,-23,24
L6, 25,28
L7, 27,30
L8, 31,35
L9,-38,40
b0,  0.1,89

This data keeps on continuing in the same sequence (i.e., b1,b2,b3...) till a large number. I want to read each of the two numbers of b0...b4 (i.e., those separated by commas in each row) in a matrix format so I can do further calculations with them. Basically each b0 occurs every 15 lines in the "file.txt" and so on for b1,b2,b3,b4. I tried using some sample codes with "textscan" but unfortunately I received errors. Any help would be much appreciated. Thanks!

Upvotes: 2

Views: 483

Answers (4)

p8me
p8me

Reputation: 1860

As well as textscan you can use importdata (however textscan might be faster):

content = importdata('Samp.txt');

then content.rowheaders would contain labels (which are repeated of course). And content.data encapsulates all the numbers:

Data = content.data;

Then using mat2cell and reshape you can do the trick:

Grouped = mat2cell(Data, ones(size(Data,1),1));

This way you will combine data for each label in a cell. Then using:

Mat = reshape(Grouped, [15 size(Data,1)/15]);

Mat would be a cell array containing the whole data in a sorted manner. Mat{1,:} is b0 data for its all occurrences (or use Mat(1,:) to get the cell array of all b0 data).

Hope it helps.

Upvotes: 0

erikced
erikced

Reputation: 732

Since you have comma-separated values you need to change the delimiter used by textscan. To combine the two numbers into an array you could use the CollectOutput option:

fid = fopen('sample.txt');
C = textscan(fid, '%s %f %f', 'Delimiter', ',', 'CollectOutput', true);
fclose(fid);

To extract all b0 fields:

values = C{2}(strcmp(C{1}, 'b0'), :);

and to extract the values of all lines beginning with b0, ..., b4

values = C{2}(ismember(C{1}, {'b0', 'b1', 'b2', 'b3', 'b4'}), :);

Upvotes: 0

aardvarkk
aardvarkk

Reputation: 15996

Here's my approach. It sucks to use a for loop in MATLAB, but I find whenever I work with cells I get caught using them. There's probably a nicer way to do this, but this appears to work for the data you gave me.

f = fopen('data.txt');
a = textscan(f, '%s', 'Delimiter', ',');
names  = [];
vals_a = [];
vals_b = [];
for i = 1:3:numel(a{1})
    names  = [names;  a{1}{i+0}];
    vals_a = [vals_a; str2num(a{1}{i+1})];
    vals_b = [vals_b; str2num(a{1}{i+2})];
end
fclose(f);

Upvotes: 0

Marcio
Marcio

Reputation: 1733

Open the file, and read each column with the appropriate conversion specifier.

fileID = fopen('scan1.txt');
C = textscan(fileID, '%s %s %f32 %d8 %u %f %f %s %f');
fclose(fileID);
celldisp(C)

see it:

Documentation Center

Upvotes: 0

Related Questions