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

2 ビュー (過去 30 日間)
Harish Kumawat
Harish Kumawat 2019 年 12 月 12 日
回答済み: Deepak 2023 年 7 月 1 日
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.

回答 (1 件)

Deepak
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);

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by