mean of nonzero elements which are in between zero elements in each column

2 views (last 30 days)
I have matrix of 4097X1000. I want to take mean of nonzero elementmean of nonzero elements which are in between zero element in each column of matrix, like
A= 1 3 5 0 0
2 0 0 2 1
3 4 5 7 1
5 3 5 0 0
3 0 0 3 1
in Matrix A I have to take means of element inbetween zero i.e. in column 2 for 4 and 3, in column 3 for 5and 5, in column 4 for 2 and 7 which between zero.

Answers (1)

Deepak
Deepak on 1 Jul 2023
You can compute the mean of non-zero elements between 0s in each column of a matrix and store them with the following method:
% Example matrix
myMatrix = [1 3 5 0 0; 2 0 0 2 1; 3 4 5 7 1; 5 3 5 0 0; 3 0 0 3 1];
% Initialize the array to store column means
columnMeans = zeros(1, size(myMatrix, 2));
% Loop through each column
for col = 1:size(myMatrix, 2)
% Find the indices where 0 appears in the current column
zeroIndices = find(myMatrix(:, col) == 0);
if(size(zeroIndices) < 2)
columnMeans(col) = 0;
else
first = zeroIndices(1);
last = zeroIndices(end);
sum = 0;
cnt = 0;
for row = first:last
if(myMatrix(row , col) > 0)
sum = sum + myMatrix(row , col);
cnt = cnt + 1;
end
end
columnMeans(col) = sum/cnt;
end
end
% Display the column means
disp(columnMeans);

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!