필터 지우기
필터 지우기

How to import .csv files, keeping all the headers (which are on multiples rows) in order to extract some information from the headers?

조회 수: 3 (최근 30일)
Hi!
I have a bunch of .csv files that I have to manipulate and some information that I need is stored in the headers.
Such files are organized in this way:
  • from row 1 to row 21, organized in just one column, there are headers (strings) containing some information I need (regarding the experiments I have done);
  • row 22 contains the proper headers in two columns;
  • from row 23 to 1361 there are the values (numbers) related to the headers in row 22.
I leave here attached one of those files that I would like to analyse.
So I need to access to the values in row 7 and row 15, which are both constant for each file. For example, in the case of the file attached, the values are respectively "# CenterZ = -7923.190" and "# Power2 = 1.161346e-06". Then, I have to store from row 7 the number -7923.190 and for row 15 the number 1.161346e-06. Those values change from .csv to csv.
Do you have any idea on how I could proceed? I have checked the community posts with no success...
Hope I have been cleared in the explanation.

채택된 답변

Scott MacKenzie
Scott MacKenzie 2022년 2월 24일
편집: Scott MacKenzie 2022년 2월 24일
Assuming your files are consistently formatted, here's one way to extract the data values in the header lines and then read the data after the header lines into a matrix:
f = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/906250/end_cavity1_v5_Z_-2.0000_2Power_0.0150_Spectrum.csv';
C = readcell(f, 'range', '1:21');
C7 = C{7};
CenterZ = str2double(C7(13:end))
CenterZ = -7.9232e+03
C15 = C{15};
Power2 = str2double(C15(13:end))
Power2 = 1.6135e-07
M = readmatrix(f); % extract the data starting after the header lines
  댓글 수: 2
Scott MacKenzie
Scott MacKenzie 2022년 2월 25일
@Pietro Tassan You're welcome. Glad to help.
BTW, below is another way to extract values from the header lines. This method is a bit cleaner, I think:
s = split(C(7));
CenterZ = str2double(s(4))
s = split(C(15));
Power2 = str2double(s(4))

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by