How to remove \n and empty line after combine all the lines into an array

I have a txt file 'map1.txt'
1 Ai.A
2 i.i.
3 .Aii
4 AiiA
I want to concatenate all the lines of the file into an array.
'Ai.A'
'i.i.'
'.Aii'
'AiiA'
However, my arr includes and ' '
'Ai.A↵'
'i.i.↵'
'.Aii↵'
'AiiA↵'
' '
Can anyone show me how to remove and ' '
This is my code. Thank you for your help!!!
fh = fopen('map1.txt')
line = fgets(fh)
vec = [line]
while ischar(line)
line = fgets(fh);
vec(end+1,:) = line;
end

 Respuesta aceptada

per isakson
per isakson el 15 de Jun. de 2019
Editada: per isakson el 15 de Jun. de 2019
Replace
fgets
by
fgetl
fgetl, Read line from file, removing newline characters
In response to comment
To remove the ending "blank" row, replace
while ischar(line)
by
while not(feof(fh))
while not(feof(fh)) avoids reading one or more trailing empty lines, i.e. lines containing only newline characters.
To remove trailing rows that contains pure white-space add these lines to the end of the script
while isempty(strtrim(vec(end,:)))
vec(end,:)=[];
end

6 comentarios

thank you. I still get ' ' at the end. How can I delete it??
per isakson
per isakson el 15 de Jun. de 2019
Editada: per isakson el 15 de Jun. de 2019
Are you sure there isn't a last line in the file, which contains a few spaces?
The txt file has an empty line at line 5. I forgot to post it. That why I got an ' ' when creating an array. How can I remove it from my array?? Thank you
"I still get ' ' at the end. How can I delete it??"
strtrim or deblank
thank you!!
Surprice! The last row are not spaces, it's nulls
>> double(vec)
ans =
65 105 46 65
105 46 105 46
46 65 105 105
65 105 105 65
0 0 0 0
The last row is caused by one trailing empty line in combination with while ischar(line)
See the addendum to my answer.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Preguntada:

el 15 de Jun. de 2019

Editada:

el 15 de Jun. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by