Replacing elements of a text file

Dear community, i already searched for my matter but i do not find any good reply. Btw, i have a text file "map.txt" composed by different letters in a 25x60 matrix.
And i need to rewrite this matrix in a new text file replacing all the letters different from "i" with an "e" (it's an academic exercise). I really have different difficulties loading the file.
My idea was using some code like this one:
filename='mappa.txt';
delimiterIn='';
headerlinesIn=25;
A=importdata(filename,delimiterIn,headerlinesIn);
[n,m]=size(A);
Aout=zeros(size(A));
for i=1:n
for j=1:m
if (A(i,j)==('I'))
Aout(i,j)=('X');
else
Aout(i,j)=('~');
end
end
end
disp=(Aout)
but it obviously doesn't work. Any suggestion? Kindly, A.

2 Comments

importdata is for numeric, not character data.
Would need sample of the file to know precisely the input, but to do a simple character substitution, look at
doc strrep
just resolved using
while ~feof(fin)
s=fgetl(fin);
m=size(s,2);
for i=1:m
if (s(i)==a)
s(i)=('X');
else
s(i)=('~');
end
end
disp(s);
fprintf(fout,'%s\n',s);
thanks for ur reply

Sign in to comment.

 Accepted Answer

Stephen23
Stephen23 on 5 Oct 2015
Edited: Stephen23 on 6 Oct 2015
This is easy to do using some simple commands:
>> str = fileread('mappa.txt');
>> idx = str~='i' & isstrprop(str,'alpha');
>> str(idx) = 'e';
>> fid = fopen('newfile.txt','w');
>> fprintf(fid,'%s',str);
>> fclose(fid);
Where the original file looks like this:
qwert
yuiop
uoiow
iupwo
and the newfile looks like this:
eeeee
eeiee
eeiee
ieeee
I had to invent my own data because you did not provide us with any test-file for us to test our code with. If you attach your data in a comment then we can check that it works properly with your data too.
Note that I assumed that the file contains only alphabetic characters. Your final algorithm depends on what you mean by "all the letters different from "i"": for example the newline character is different from i, should this also be replaced by e? You can adjust this behavior by changing the isstrprop category string.

2 Comments

I'm really sorry for this. As i already said, i'm a newbie of this community. I'll provide something more detailed next time.
Btw, i really never read anything about isstrprop. The file contains only alphabetic characters; i'll try rewriting my code asap.
Thanks for your time.
If "The file contains only alphabetic characters", then how can it be arranged in a matrix without any newline characters?

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!