Accessing multiple columns in cell array

3 ビュー (過去 30 日間)
Lasse Jakobsen
Lasse Jakobsen 2021 年 6 月 9 日
回答済み: Stephen23 2021 年 6 月 9 日
Hi,
I need to calculate the mean of 5 measurements. The 5 measurements are presented in a 5*1 cell array. The variable is called Data.
Thus, I need the mean of:
Data{1, 1}(:,end)
Data{2, 1}(:,end)
Data{3, 1}(:,end)
Data{4, 1}(:,end)
Data{5, 1}(:,end)
How do I acces all 5 columns at once?
Thanks in advance.
-Lasse

回答 (3 件)

KSSV
KSSV 2021 年 6 月 9 日
編集済み: KSSV 2021 年 6 月 9 日
A = cat(3,Data{:}) ; % convert cell array to 3D matrix
m = cell2mat(mean(A(:,end,:))) % mean of last column

Scott MacKenzie
Scott MacKenzie 2021 年 6 月 9 日
編集済み: Scott MacKenzie 2021 年 6 月 9 日
You need to retrieve the elements in their underlying data type (hence the use of braces) and concatenate the values using brackets:
mean([Data{:,1}])
If indeed thare are only 5 values (measurements), then you don't need ",1". Just use
mean([Data{:}])
Have a look here for a summary of the ways to access data in a cell array. Good luck.

Stephen23
Stephen23 2021 年 6 月 9 日
Fake data:
Data = arrayfun(@(n)randi(9,2,3),1:5,'uni',0).'; % fake data
Data{:}
ans = 2×3
2 5 6 6 5 4
ans = 2×3
9 3 5 1 3 5
ans = 2×3
3 1 9 8 5 2
ans = 2×3
5 6 6 2 4 1
ans = 2×3
2 7 2 1 7 5
Method one:
M = mean(cat(3,Data{:}),3);
M = M(:,end)
M = 2×1
5.6000 3.4000
Method two:
M = mean(cell2mat(reshape(Data,1,1,[])),3);
M = M(:,end)
M = 2×1
5.6000 3.4000
Method three:
M = mean(cell2mat(cellfun(@(m)m(:,end),Data.','uni',0)),2)
M = 2×1
5.6000 3.4000
Method four:
M = mean(cell2mat(arrayfun(@(n)Data{n}(:,end),1:numel(Data),'uni',0)),2)
M = 2×1
5.6000 3.4000

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by