How can I calculate mean of elements in a column of a cell array?

13 ビュー (過去 30 日間)
Behrooz Daneshian
Behrooz Daneshian 2023 年 1 月 26 日
回答済み: Vinayak Choyyan 2023 年 2 月 8 日
Hi all,
I have cell array called "stations2". I intend to calculate the avearge of numbers in 2nd column of this cell and insert it below the last element of that column. Can anyone help me in this regard?
  1 件のコメント
Stephen23
Stephen23 2023 年 1 月 26 日
"I intend to calculate the avearge of numbers in 2nd column of this cell"
Where C is your cell array:
v = mean([C{:,2}])

サインインしてコメントする。

回答 (1 件)

Vinayak Choyyan
Vinayak Choyyan 2023 年 2 月 8 日
Hi Behrooz,
As per my understanding, you have a cell array, stations2, with 10 rows and 20 columns. You would like to find the mean of the second column and append the result to below the 10th row.
Unfortunately, a cell array can not be of any variable size in a given direction. Hence, we would need to append an entire row to the cell array stations2. This new 11th row can have the desired mean in its second column but would have garbage value in all other columns, which you would have to ignore using code as per your use case. Here is one way you can do this.
clc;clear;
load('stations2.mat');
%find mean of second column
tempMean = mean([stations2{:,2}]);
%add a 11th row at the end. I have inserted []. Do adjust this to a
%different value as per your use case
[stations2{end+1,:}]=deal([]);
%insert mean below the 10th element of 2nd columns
stations2(end,2)={tempMean}
I hope this resolves the issue you were facing. Please refer to the following documentation to read more about:

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by