Extracting specific rows from multiple data files to store as variables

조회 수: 13 (최근 30일)
I'm very new to Matlab.
I have multiple data files (file type file) of dimensions 5x12001, each representing data from an experiment.
For each file I want to extract the first two rows (i.e. to have a 2x12001 matrix from each file (or two 1x matrices)) and store in such a way that allows me to keep track of which stems from which file.
I've tried generating a cell array:
files = dir('*.');
files = files(~ismember({files.name},{'.', '..'})); %gets rid of empty files invisible in explorer
for i = 1:length(files)
C{i} = load(files(i).name);
end
But I'm not sure how to efficiently manipulate the matrices once indexed in a cell array.
This crappy function sort of represents what I'm trying to achieve:
function [wavelength, datavalue] = getmatrix(filename)
matrix = readmatrix(filename);
wavelength = matrix(1,:);
datavalue = matrix(2,:);
end
But I'd like to be able to loop through all the files without having to manually call the function on each filename.
Thanks, and sorry for my staggering ineptitude.

채택된 답변

Stephen23
Stephen23 2019년 6월 17일
편집: Stephen23 2019년 6월 17일
"....and store in such a way that allows me to keep track of which stems from which file."
That is easy using the structure returned by dir:
S = dir('*.csv'); % better to specify the file extension!
for k = 1:numel(S)
tmp = load(S(k).name); % you should probably use DLMREAD or similar.
S(k).data = tmp(1:2,:) % 1st & 2nd rows.
% OR
S(k).wavelength = tmp(1,:); % 1st row.
S(k).datavalue = tmp(2,:); % 2nd row.
end
  댓글 수: 1
Alexander Collins
Alexander Collins 2019년 6월 17일
That's great Stephen, thanks!
I was initially confused how to reference the actual data in the structure array (as linked in the top-left cell of the attached picture), but I realised I can just refer to is as, for example, S(1).data(1,:) (for the first row of the first file in structure S).

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Workspace Variables and MAT Files에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by