How to iterate through a cell array to mean each ith column from each matrix within the cell array?

1 次查看(过去 30 天)
I have a data set which is structured as a 3x5 cell array where each row of this cell array has a matrix with a different number of columns. I need to extract the ith column from each matrix within the first row of the cell array, average those values together, and then output them into a new variable which is the same dimensions as one of the matrices in the first row of the cell array (they're all the same dimensions). So taking the first column from each of the matrices, inputting them into a new matrix, averaging those values, and then repeating for the 2nd column, then the third column, ith column. Then I need to repeat this for the 2nd and 3rd rows of the cell array. When I try to loop through this I get stuck at the part where I need to extract the ith column from each of the matrices before iterating to the next column:
%% Creating example data
for j=1:3
for k=1:5
data{1,k} = rand(500,26);
data{2,k} = rand(500,24);
data{3,k} = rand(500,27);
end
end
% Pre-allocate final variable
data_final = cell(3,1);
for j=1:3
[nsamp,ntraces] = size(data{j,1});
for k=1:5
dataPull = zeros(nsamp,5);
for l=1:ntraces
dataPull(:,k) = data{j,k}(:,l); % stuck here
dataTemp = mean(dataPull,2); % need to avg only after pulling all 5 columns
data_final{j}(:,l) = dataTemp;
end
end
end

回答(1 个)

Stephen23
Stephen23 2025-3-6
编辑:Stephen23 2025-3-6
Fake data (I removed the superfluous outer loop):
for k = 1:5
C{1,k} = rand(500,26);
C{2,k} = rand(500,24);
C{3,k} = rand(500,27);
end
Method 1: using CELLFUN:
F = @(c) mean(cat(3,c{:}),3);
A = cellfun(F,num2cell(C,2),'uni',0)
A = 3x1 cell array
{500x26 double} {500x24 double} {500x27 double}
Method 2: using a FOR loop:
B = C(:,1); % preallocate
for k = 1:numel(B)
B{k} = mean(cat(3,C{k,:}),3);
end
Checking:
isequal(A,B)
ans = logical
1
Both of these approaches use a comma-separated list inside CAT():

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by