Search code examples
matlabmatlab-guidematlab-deployment

How to change the zeros of the matrix in anterior number of the matrix?


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]


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!