User1961
User1961

Reputation: 131

MATLAB string 2 number of table

I have a 3-year data in a string tableformat.txt. Three of its lines are given below:

12-13 Jan -10.5
14-15 Jan -9.992
15-16 Jan -8

How to change the 3rd column (-10.5, -9.992 and -8) of string to be (-10.500, -9.992 and -8.000) of number?

I have made the following script:

clear all; clc; 
filename='tableformat.txt'; 
fid = fopen(filename); 
N = 3;
for i = [1:N]
    line = fgetl(fid)
    a = line(10:12);
    na = str2num(a);
    ma(i) = na;
end
ma

which gives:

ma = -1    -9    -8

When I did this change: a = line(10:15);, I got:

Error message: Index exceeds matrix dimensions.

Upvotes: 0

Views: 71

Answers (1)

Waseem Anwar
Waseem Anwar

Reputation: 301

This will work for you.

clear all;

clc;

filename='tableformat.txt';
filename2='tableformat2.txt';

fid = fopen(filename);
fid2 = fopen(filename2,'w');

formatSpec = '%s %s %6.4f\n';

N = 3;

for row = [1:N]

line = fgetl(fid);
a = strsplit(line,' ');
a{3}=cellfun(@str2num,a(3));
fprintf(fid2, formatSpec,a{1,:});

end

fclose(fid);

fclose(fid2);

Upvotes: 2

Related Questions