Question

I have the matrix of 3 x 8, in the matrix I have to excluded the zeros and use the anterior number on the column. Posteriorly, I use the elements of the column for calculate the mean. As you can see, the mean of the column should be between 4.8500 and 4.9900. I hope I have been clear. I thank a lot of attention.

[4.8500 4.8900 4.9000 4.8600 4.9900 4.9200 4.9600 4.9600 4.9200 4.8900 4.9000 4.9000 4.9000 4.9800 4.9500 0 4.9000 4.8600 4.9000 4.9300 4.9200 4.9500 0 0]

Was it helpful?

Solution

I am assuming you are looking to calculate column-wise means without considering the zeros.

Code

a = [4.8500 4.8900 4.9000 4.8600 4.9900 4.9200 4.9600 4.9600 4.9200 4.8900 4.9000 4.9000 4.9000 4.9800 4.9500 0 4.9000 4.8600 4.9000 4.9300 4.9200 4.9500 0 0];
a = reshape(a',[8 3])'
a(a==0)=NaN;
mean_columnwise = nanmean(a,1)

The trick that worked here is to convert all zeros into NaNs and then using nanmean, which calculates mean values ignoring the NaNs that were zeros previously.

Output

a =

    4.8500    4.8900    4.9000    4.8600    4.9900    4.9200    4.9600    4.9600
    4.9200    4.8900    4.9000    4.9000    4.9000    4.9800    4.9500         0
    4.9000    4.8600    4.9000    4.9300    4.9200    4.9500         0         0


mean_columnwise =

    4.8900    4.8800    4.9000    4.8967    4.9367    4.9500    4.9550    4.9600

Let us know if this is what you are after!

OTHER TIPS

matrix = [4.8500 4.8900 4.9000 4.8600 4.9900 4.9200 4.9600 4.9600
          4.9200 4.8900 4.9000 4.9000 4.9000 4.9800 4.9500 0     
          4.9000 4.8600 4.9000 4.9300 4.9200 4.9500 0      0]; %// example data

while true %// a loop is used in case there are runs of zeros
    ii = find(matrix==0); %// linear indices of zeros
    if isempty(ii)
        break %// there are no more zeros: exit loop
    end
    matrix(ii) = matrix(ii-1); %// replace zero with preceding value.
    %// That preceding value may also be zero, but that will be taken
    %// care of in the next iteration
end
result = mean(matrix); %// column-wise mean
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top