Importing only specific entries from a text file to matlab
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
Hello,
I am trying to import a text file, but do not need all the information, just only specifics (after the : operator). Here is a sample version of the text file
Select type (A or B or C): C Enter the number of days: 30 Select test type (Reg or Mod): Reg Enter the number of TC's used: 1
The data is a mix of alphanumeric and numeric. So I need something that handle both. Any help will be appreciated. Thanks
채택된 답변
Regular expressions are probably your best option. Look at the following:
>> s = 'Select type (A or B or C): C Enter the number of days: 30 Select test type (Reg or Mod): Reg Enter the number of TC''s used: 1' ;
>> results = regexp(s, '(?<=:\s+)\S+', 'match')
results =
'C' '30' 'Reg' '1'
The second argument in the call to REGEXP is the pattern. Let me know if you need help to understand it.
댓글 수: 6
Yes surely need some help. Here is the code to which I need to add the features:-
[ffname,pathname] = uigetfile('*.txt', 'Select Input Parameters File');
fname = strcat(pathname,ffname);
ffname;
fid = fopen(ffname,'r'); % Open text file
InputText=textscan(fid,'%s',4,'delimiter','\n');
Intro=InputText{1};
disp(Intro1);
Try the following
[ffname,pathname] = uigetfile('*.txt', 'Select Input Parameters File');
buffer = fileread(fullfile(pathname, ffname)) ;
results = regexp(buffer, '(?<=:\s+)\S+', 'match')
FILEREAD will open/read the file and return its content as a string. It is better to use FULLFILE than STRCAT for concatenating path elements; FULLFILE manages specifics of the operating system that you are running (e.g. / and \).
REGEXP does pattern matching. The pattern is defined by its 2nd argument. The regexp engine reads buffer (given as 1st argument) until it matches the pattern, extracts the match, and goes on iteratively. The output is a cell array with all the matches.
Cedric,
Thanks. I am able to read the file. But I do have another question if I can. My input files has both strings and numeric. When I use the above approach, it by default stores it as cell array. I am able to re-assign the certain cell inputs as string by using char function, is there something I can use to re-assign certain cell inputs to numeric ?
Example:-
C = {'one', 'two', 'three', '1','2','3'}
D = char(C(1,1))
As you can see C(1,1), C(1,2) and C(1,3) are string inputs while C(1,4), C(1,5) and C(1,6) needs to be numeric.
Again thanks for your time and appreciate your help.
Krish,
>> C = {'one', 'two', 'three', '1','2','3'}
>> C(1)
ans =
'one'
>> class(ans)
ans =
cell
Here you can see that the class/type of C(1) is cell and not char. Cells are containers; to access their content, you need {} indexing:
>> C{1}
ans =
one
>> class(ans)
ans =
char
So C(1) gives cell #1 and C{1} gives the content of cell #1. As mentioned above, C is a 1D cell array with 6 cells. Each cell content is a string. So you are in a situation where you will just access the content of cells whose content has to be used as strings, and you will access + convert to a numeric type the content of cells whose content has to be treated as numbers.
>> C{2}
ans =
two
>> class(ans)
ans =
char
here you have directly a string (type=char), there is no need to convert to char.
>> C{6}
ans =
3
>> class(ans)
ans =
char
Now here you have a string as well, that you want to convert to a numeric type, e.g. double..
>> str2num(C{6})
ans =
3
>> class(ans)
ans =
double
or ..
>> str2double(C{6})
ans =
3
Now you can still use () on C to extract one cell as seen above, or blocks of cells, e.g.
>> C(4:6)
ans =
'1' '2' '3'
>> class(ans)
ans =
cell
here, we indexed the block 4:6 of the cell array C. This is a cell array as well. Now some functions are able to read the content of cells when you provide them with cell arrays instead of simply the type/class that they are meant to operate on. Typically, STR2DOUBLE can take a cell array of strings, and convert it to an array of double:
>> str2double(C(4:6))
ans =
1 2 3
>> class(ans)
ans =
double
Hope it helps!
Got it. Sure make a difference when you have someone to take the time to explain. Its hard to figure something this simple when you have to read it from a text by yourself.
Again thanks a lot for your time and effort.
You're welcome!
Indexing is not the simplest thing to understand by ourselves actually, this is why I gave a little more explanations than usual. Paradoxically, understanding how to solve nice enough differential equations with MATLAB is simpler than understanding basic data structure and indexing.
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
