For loop getting array name
4 views (last 30 days)
Show older comments
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 Comments
Answers (2)
Walter Roberson
on 21 Jun 2021
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 Comments
Stephen23
on 22 Jun 2021
Edited: Stephen23
on 22 Jun 2021
"Can you elaberate on what is hapening here?"
Poor data design is forcing you into writing complex, inefficient code that is difficult to work with.
The simple, efficient approach is to use indexing into one array, just as the MATLAB documentation shows:
Stephen23
on 22 Jun 2021
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 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!