Manipulating a text file

7 views (last 30 days)
james flynn
james flynn on 7 Apr 2017
Commented: Walter Roberson on 10 Apr 2017
Hi all. I am trying to replace one of the columns within my text files with a column of zeros. I have been trying to do this by reading each of the columns in the file, replacing the desired column with a matrix of 0's and then writing this to a new file. When running the code the following error is produced which i havent seen before:
Error using horzcat Dimensions of matrices being concatenated are not consistent.
Error in ZlessData (line 13) J = [J1 J2 J3 J4 J5];
Here's the code and data file. Can anyone help?
function ZlessData
Jupiter = dlmread('1959-2019Jupiter.txt');
J1 = Jupiter(:,1);
J2 = Jupiter(:,2);
J3 = Jupiter(:,3);
J5 = Jupiter(:,5);
x = (size(Jupiter,1));
J4(1,x) = 0
J = [J1 J2 J3 J4 J5];
fidJ = fopen('1959-2019JupiterZless','w');
fprintf(fidJ, '%f %f \r\n', [J]');
fclose(fidJ);

Accepted Answer

Walter Roberson
Walter Roberson on 7 Apr 2017
function ZlessData
Jupiter = dlmread('1959-2019Jupiter.txt');
J = Jupiter;
J(:,4) = 0;
fidJ = fopen('1959-2019JupiterZless','w');
fprintf(fidJ, '%f %f \r\n', [J]');
fclose(fidJ);
  2 Comments
james flynn
james flynn on 10 Apr 2017
Thank you. However, it still changes the layout of the document into what seems to be like a continuous string of data. I require the document to have the data layed out in rows like this, as it is in the original document:
1993 1 0.983 0.00 100.58 -3.04 264.11 24.73
1993 2 0.983 0.00 101.60 -3.16 251.00 25.75
1993 3 0.983 0.00 102.62 -3.27 237.82 26.76
1993 4 0.983 0.00 103.64 -3.39 224.65 27.78
1993 5 0.983 0.00 104.66 -3.50 211.48 28.79
Walter Roberson
Walter Roberson on 10 Apr 2017
S = fileread('1959-2019Jupiter.txt');
linelen = find(S==10,1,'first');
Scol = reshape(S, linelen, []).';
Scol(:,18:19) = ' ';
Scol(:,20:23) = '0';
Scol(:,21) = '.';
fidJ = fopen('1959-2019JupiterZless.txt','w');
fwrite(fidJ, Scol.');
fclose(fidJ);
Note: the code in the above form relies upon each line being exactly the same length and the column widths being exactly what your file has.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!