MATLAB Answers


write data to specific column in text file

Asked by Lalit Patil on 20 Nov 2012

I have this text file created from

I = imread('3.jpg');
i = im2bw(I);
m = max(max(i));
[r c] = find(i == m);
fid = fopen('lalit.txt','wt');
for j=1:length(r)
fprintf(fid,'%f %f\n',r(j),c(j));
 Now i want to do 
for m = 1:length(r)
z(m) = round((r(m) + c(m))/2);

Now i want to save this z as third column in the same text file, but without modifying r and c.



No products are associated with this question.

1 Answer

Answer by Walter Roberson
on 20 Nov 2012
 Accepted answer

The only way you should seriously consider for modifying data in text files is to read in the file and write the modified version to another file, possibly followed by renaming the new file to the old name. Modifying a text file "in place" is tricky and often not possible anyhow.

  1 Comment

clear all; clc; I = imread('1.jpg'); i = im2bw(I); imshow(i); m = max(max(i)); [r c] = find(i == m); a = r; fid = fopen('lalit.txt','wt'); for j=1:length(r) fprintf(fid,'%f %f\n',r(j),c(j)); end fclose(fid);

data = textread('lalit.txt'); a = unique(data); for i=a', maxVal = max(data(a==i,2)); minVal = min(data(a==i,2)); z(i,:) = round((maxVal + minVal)/2); end

fid = fopen('lalit1.txt','wt'); for j=1:length(z) fprintf(fid,'%f\n',z(j)); end fclose(fid);

Thank you.. I got it.. it doesn't matter for me whethere i write data to same file or another file..

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!