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

14 views (last 30 days)
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 Comment
Stephen23
Stephen23 on 26 Jan 2023
"I intend to calculate the avearge of numbers in 2nd column of this cell"
Where C is your cell array:
v = mean([C{:,2}])

Sign in to comment.

Answers (1)

Vinayak Choyyan
Vinayak Choyyan on 8 Feb 2023
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:

Tags

Community Treasure Hunt

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

Start Hunting!