mean of nonzero elements which are in between zero elements in each column
2 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
Deepak
2023-7-1
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);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!