Import multiple text files to separate arrays

I have 3 text files with 17 columns of numeric data and varying row size. I am trying to import the text files, and assign them to their own matrix so I can compare file1 to file 2, etc. I have used textscan and can get all of the data into a cell array, but am unsure how to get separate cell arrays for each file so if I have 3 or 5 or 10 files, it would work the same.
The error I currently get is "Unable to perform assignment because the indices on the left side are not compatible with the size of the right side." I believe this is because I have a "temp" variable with only 3 columns compared to the 17 columns I am importing. But I am unsure how to rectify the problem. This is what I have so far using MATLAB 2018b.
clc
clear
cd H:\MATLAB\Practice
files = dir('*.txt');
for i = 1:length(files)
fid = fopen(files(i).name);
temp(:,i) = cell2mat(textscan(fid,'%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f','Delimiter','\t','CollectOutput',1));
fclose(fid);
end

1 件のコメント

Walter Roberson
Walter Roberson 2019 年 2 月 23 日
Assign to temp{i} instead of temp(:,i)

サインインしてコメントする。

 採用された回答

Stephen23
Stephen23 2019 年 2 月 23 日

0 投票

Following the examples in the MATLAB documentation:
and avoid using cd in code. For example:
fmt = repmat('%f',1,17);
opt = {'Delimiter','\t','CollectOutput',true};
D = 'H:\MATLAB\Practice';
S = dir(fullfile(D,'*.txt'));
N = numel(S);
C = cell(1,N);
for k = 1:N
fid = fopen(fullfile(D,S(k).name));
C(k) = textscan(fid,fmt,opt{:});
fclose(fid);
end

1 件のコメント

L1n022
L1n022 2019 年 2 月 23 日
Thank you for the help with the problem and cleaning up my code! Works great!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

製品

リリース

R2018b

質問済み:

2019 年 2 月 23 日

コメント済み:

2019 年 2 月 23 日

Community Treasure Hunt

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

Start Hunting!

Translated by