How to grab first number from each line of a .txt file and store it in a vector?

조회 수: 7 (최근 30일)
I want to grab first number from each line and store it in a vector. I am trying in following way. But, the written code is picking all numbers from the file. I have attached here the input.txt file. Can anybody please help me regarding this? Thank you.
My written code:
fid = fopen('input.txt');
matrix = fscanf(fid, '%d', [1,inf]);
disp(matrix)
Matlab Output:
1 3 4 8 2 -1 0 8 3 4 5 6 7 8 9 -2
I wanted to grab only(the first number from each line):
1 3 2 3 4 5 6 7 8

채택된 답변

Walter Roberson
Walter Roberson 2020년 2월 9일
fid = fopen('input.txt');
matrix = cell2mat( textscan(fid, '%f%*[^\n]') ); %second field skips to end of line
fclose(fid);
  댓글 수: 4
Shuvashish Roy
Shuvashish Roy 2020년 2월 10일
Thanks a lot for your time and patience. You are really very kind and awesome!
Preyanka Dey
Preyanka Dey 2020년 2월 10일
Thank you so much. Finally, I got it. You are really very kind.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by