Changing the variable names for multiple tables within a loop that imports the data

8 ビュー (過去 30 日間)
I have imported a series of text files using the code posted below and the headers are 'x_________', 'x_______1' etc. I have been able to change the headers manually using T.Properties.VariableNames but for a set of 6 tables with 5 columns each this gets tedious, plus I will be importing multiple table sets like this. I want the same column headers across all of the tables (i.e. the variable names themselves are not dynamic). How can I incorporate this into the for loop in order to save time and space? Thanks!
for i=[0:10:50]
filename = ['UCS_stress_',num2str(i),'.txt'];
eval(['per_' num2str(i) '= readtable(filename)'])
end

採用された回答

Stephen23
Stephen23 2021 年 5 月 23 日
編集済み: Stephen23 2021 年 5 月 23 日
Using eval is a misdirection that forces you into writing slow, inefficient, complex code:
It is much simpler and more efficient to use basic indexing, just like MATLAB was designed for:
C = {cell array of the five table variable names};
V = 0:10:50; % those square brackets were superfluous.
N = numel(V)
T = cell(1,N); % preallocate cell array.
for k = 1:N
fnm = sprintf('UCS_stress_%d.txt',V(k));
tmp = readtable(fnm);
tmp.Properties.VariableNames = C;
T{k} = tmp; % basic indexing.
end
  2 件のコメント
Amy M
Amy M 2021 年 5 月 23 日
Hi Stephen, thanks for your help. I'm not sure if this is just me misunderstanding the code, but when I run this I only get one table as opposed to six.
Stephen23
Stephen23 2021 年 5 月 24 日
"...but when I run this I only get one table as opposed to six."
Did you look inside the cell array T ? All six of the tables are stored in there.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by