How to import part of the data from multiple .txt files into the MATLAB workspace as a variable

1 view (last 30 days)
I have two .txt files in my directory that I want to load part of the data into a workspace variable. Both files have the same format (data starts on line 54 and ends on line 254) but different names. One is named '685_FM01_HF_7-21-2020.txt' and the other is '685_InM01_HF_7-21-2020-000019-t01-RAW.txt'. Unfortunately, I am not allowed to upload the actual .txt files by my company, but the data is formatted as follows:
-1224.895 , 34456674
4948540, 342342342
34234234, 3423423
8543574, 224234235
8049865, 4830958
Two columns, with a comma as the delimiter. Is there a way to import the data from the two textfiles into two different workspace variables? I tried using the 'import data' feature in MATLAB's interface, but it only does one specific file.. I think I'll need a for loop, but I don't know how to format them. I started my MATLAB journey yesterday, so apologies if this a trivial answer. Thank you for any assistance you can give.

Accepted Answer

hosein Javan
hosein Javan on 12 Aug 2020
fileID = fopen('685_FM01_HF_7-21-2020.txt'); % open first text file
c1 = textscan(fileID,'%f %f','Delimiter',','); % scan it in the format of comma seperated
fclose(fileID); % close the file
c1 = cell2mat(c1); % convert to matrix
format shortG % display numbers in short format
c1 = c1(54:254,:) % select lines starting from 54 to 254
% the same thing for file2
fileID = fopen('685_InM01_HF_7-21-2020-000019-t01-RAW.txt');
c2 = textscan(fileID,'%f %f','Delimiter',',');
fclose(fileID);
c2 = cell2mat(c2);
c2 = c2(54:254,:)

More Answers (0)

Community Treasure Hunt

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

Start Hunting!