generating an array from the same element across several tables
조회 수: 2 (최근 30일)
이전 댓글 표시
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
채택된 답변
Sanskar
2023년 6월 14일
편집: Sanskar
2023년 6월 15일
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
Dyuman Joshi
2023년 6월 14일
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')
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!