0
votes

I need to use "importdata" to run a script, but my file has more columns at the bottom than at the top, like this:

Example1

2 2 3 2
2 2 1 1
1 0
2 4
1 1 2 200000 80000

It starts with 4 columns, and ends with 5), so when I use importdata, it makes a matrix with 4 columns, damaging my file. What I wanted to do is add any number at the end of the first data row (or second text row), preferentially a 0, to make it read my file as a 5-column matrix, like this:

Example1

2 2 3 2 0
2 2 1 1 0
1 0 0 0 0
2 4 0 0 0
1 1 2 200000 80000

The zeros in the other columns are, as I understand, the result of the "importdata" in a 5-column matrix, I don't need to write them too. How can this be done?

1

1 Answers

0
votes

You can use textscan to read in your data. Here's how to read in your file:

fid = fopen('example.txt');
mat = textscan(fid,'%d %d %d %d %d','CollectOutput', 1);
mat = mat{1}; % accesses matrix from cell array
mat(isnan(mat)) = 0; % sets NaN values to 0
fclose(fid);

And the results:

mat =

           2           2           3           2           0
           2           2           1           1           0
           1           0           0           0           0
           2           4           0           0           0
           1           1           2      200000       80000

You can then save this a new file like this:

fid = fopen('newfile.txt','w');
fprintf(fid,'%d %d %d %d %d\r\n', mat);
fclose(fid); 

and read it in with importdata.