generating an array from the same element across several tables
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Matteo Tomasini
am 14 Jun. 2023
Bearbeitet: Sanskar
am 15 Jun. 2023
Hi,
I have n similar tables (same structure, different data).
I have collected all tables in a cell array, so that Tarray{1} gives the first table, Tarray{2} gives the 2nd table and so on.
Tarray{i}{2,3} gives the content (a scalar value) of the element of table i, row 2, column 3.
I would like to create an array from the scalar values contained in position (2,3) across all tables. This can be done with the following code:
array = zeros(length(Tarray),1);
for ii = 1:length(Tarray)
array(ii) = Tarray{ii}{2,3};
end
Is there a better/faster way to do that?
Thanks!
0 Kommentare
Akzeptierte Antwort
Sanskar
am 14 Jun. 2023
Bearbeitet: Sanskar
am 15 Jun. 2023
Hi Matteo!
What I understood from your question is that you want to extract elements from all tables of the given position.
The method which you are using is fast one only. Also you can look through the below code, which may also work.
% initialize cell array
Tarray = cell(1, n);
% populate cell array with tables
for i = 1:n
Tarray{i} = readtable("table_" + i + ".csv");
end
% use cellfun to extract scalar value from each table
arr = cellfun(@(table) table{2, 3}, Tarray);
cellfun(func,C) applies the function func to the contents of each cell of cell array C, one cell at a time. cellfun then concatenates the outputs from func into the output array A, so that for the ith element of C, A(i) = func(C{i}). The input argument func is a function handle to a function that takes one input argument and returns a scalar. The output from func can have any data type, so long as objects of that type can be concatenated. The array A and cell array C have the same size.
Please refer to these documentation for more information on 'cell' and 'cellfun':
Hope this answer your query.
2 Kommentare
Dyuman Joshi
am 14 Jun. 2023
Note that cellfun is slower than a for loop with pre-allocation
%Sample data
x = (1:5)';
y = (x.^2);
z = -x;
%Table
T = table(x,y,z)
%Cell array defined by repeating the same table array
C = repmat({T},1,1e2);
%cellfun
tic
for k=1:1e3
out = cellfun(@(x) x{2,3}, C);
end
timecellfun=toc
%loop with preallocation
tic
for k=1:1e3
array = zeros(length(C),1);
for ii = 1:length(C)
array(ii) = C{ii}{2,3};
end
end
timelooppre=toc
%Comparing outputs
isequal(out,array')
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!