MATLAB Answers


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

Fat Man 님이 질문을 제출함. 15 Jun 2019
최근 활동 per isakson 님이 편집함. 15 Jun 2019
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.
However, my arr includes and ' '
' '
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;

  댓글 수: 0

로그인 to comment.

답변 수: 1

per isakson 님의 답변 15 Jun 2019
per isakson 님이 편집함. 15 Jun 2019
 채택된 답변

fgetl, Read line from file, removing newline characters
In response to comment
To remove the ending "blank" row, replace
while ischar(line)
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,:)))

  댓글 수: 6

표시 이전 댓글 수: 3
"I still get ' ' at the end. How can I delete it??"
strtrim or deblank
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.

로그인 to comment.

Translated by