For loop getting array name
4 次查看(过去 30 天)
显示 更早的评论
Hi,
I am reading in a series of tables.
I then want to run a for loop performing operations on each of these tables. To do this I want to use the 'I'th name in my array.
My code looks like this:
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
%% Import the data
Table_A = readtable("Table_A", opts);
Table_B = readtable("Table_B", opts);
Table_C = readtable("Table_C", opts);
%% Defining the datasets to perform operations on
datalist = ["Table_A ","Table_B","Table_C"];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for i = [1,2,3];
ID=datalist(i); % I want this to be the table "Table_A" so that I can peform operations in this for loop
Table_ID = datalist(i); % I want this to be the string "Table_A" so that I can use it to name the heading of a table
%%%%% Now do things on the array "ID" during the for loop such as extracting data
Time= ID.Time;
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
At the end of the for loop, I am duping the data into a table.
Is there any way to achevie what I want?
Thanks!
0 个评论
回答(2 个)
Walter Roberson
2021-6-21
datalist = named_variable(Table_A, Table_B, Table_C);
%stuff
for i = 1:numel(datalist)
ID = datalist(i).content;
Table_ID = datalist(i).name;
time = ID.Time;
end
function ds = named_variable(varargin)
ds = struct('content', varargin, 'name', cell(1,nargin));
for K = 1 : nargin
name = argname(K);
if isempty(name)
error('input #%d must be a named variable not an expression', K);
end
ds(K).name = name;
end
end
2 个评论
Stephen23
2021-6-22
P = 'absolute or relative path to where the files are saved';
C = ["Table_A","Table_B","Table_C"];
N = numel(C)
D = cell(1,N);
for k = 1:N
F = fullfile(P,C{k});
D{k} = readtable(F,opts);
end
And now, exactly as you request:
for k = 1:numel(D)
ID = D{k}; % table of filedata
ID.Time
Table_ID = C(k); % table name
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!