I have a cell array called data. This is the first row.
A = {5×1 double}, B = {4×1 double}, C = {7×1 double}
I want to get the mean of each row from all cells. For example, if we cell2mat each cell we get
A = 1 B = 2 C = 3
2 4 6
3 6 9
4 8 1
5 5
6
8
I want this output, D:
D = (1 + 2 + 3)/3 = 2
(2 + 4 + 6)/3 = 4
(3 + 6 + 9)/3 = 6
(4 + 8 + 1)/3 = 4.3
(5 + 5)/2 = 5
6
8
I tried converting the cells into matrices and then combining them.
[rw,cs] = size(data);
matrix = [];
for x = 1:rw
for y = 1:cs
matrix = cell2mat(data(x, y));
matrix(n) = data;
end
end
This returns an error that: Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.

 채택된 답변

DGM
DGM 2021년 11월 20일
I'm sure there are more elegant ways than this, but eh.
celery = {(1:5).' (2:2:8).' [3 6 9 1 5 6 8].'}
celery = 1×3 cell array
{5×1 double} {4×1 double} {7×1 double}
n = cellfun(@numel,celery);
D = nan(max(n),numel(celery));
for k = 1:numel(celery)
D(1:n(k),k) = celery{k};
end
Dm = mean(D,2,'omitnan')
Dm = 7×1
2.0000 4.0000 6.0000 4.3333 5.0000 6.0000 8.0000

댓글 수: 3

Thanks for your response. However, when I tried to extend your code to a cell array with more than 1 row, it runs into a problem. It takes the max of the longest cell array instead of the max in each row.
celery = {(1:5).' (2:2:8).' [3 6 9 1 5 6 8].'};
carrot = {(1:10).' (3:3:24).' [1 3 9 1 8 1].'};
celery = [celery; carrot]
celery = 2×3 cell array
{ 5×1 double} {4×1 double} {7×1 double} {10×1 double} {8×1 double} {6×1 double}
Dm = {};
n = cellfun(@numel,celery);
[rows, cols] = size(n);
for i = 1:rows
max_value = max(n(i, :));
test_matrix = nan(max_value, numel(celery));
for k = 1:numel(celery)
test_matrix(1:n(k), k) = celery{k};
end
Dm{i} = mean(test_matrix, 2, 'omitnan');
end
Dm{1}, Dm{2}
ans = 10×1
1.8333 3.8333 6.5000 5.0000 7.6000 7.7500 12.0000 5.3333 1.5000 1.6667
ans = 10×1
1.8333 3.8333 6.5000 5.0000 7.6000 7.7500 12.0000 16.0000 9.0000 10.0000
Maybe this is closer
celery = {(1:5).' (2:2:8).' [3 6 9 1 5 6 8].'};
carrot = {(1:10).' (3:3:24).' [1 3 9 1 8 1].'};
celery = [celery; carrot]
celery = 2×3 cell array
{ 5×1 double} {4×1 double} {7×1 double} {10×1 double} {8×1 double} {6×1 double}
allveclen = cellfun(@numel,celery);
longestvector = max(allveclen,[],2);
Dm = cell(size(celery,1),1);
for i = 1:size(celery,1)
test_matrix = nan(longestvector(i),size(celery,2));
for k = 1:size(celery,2)
test_matrix(1:allveclen(i,k), k) = celery{i,k};
end
Dm{i} = mean(test_matrix, 2, 'omitnan');
end
Dm{1}, Dm{2}
ans = 7×1
2.0000 4.0000 6.0000 4.3333 5.0000 6.0000 8.0000
ans = 10×1
1.6667 3.6667 7.0000 5.6667 9.3333 8.3333 14.0000 16.0000 9.0000 10.0000
Thanks for your expertise!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

제품

릴리스

R2021a

질문:

2021년 11월 20일

댓글:

2021년 11월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by