Effacer les filtres
Effacer les filtres

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

2 vues (au cours des 30 derniers jours)
Harish Kumawat
Harish Kumawat le 12 Déc 2019
Réponse apportée : Deepak le 1 Juil 2023
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.

Réponses (1)

Deepak
Deepak le 1 Juil 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);

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by