Search code examples
matlabfor-loopif-statementmatrix

Find values greater than the mean of each column of data in a matrix


I have a matrix including 5 columns(months) and 4 rows(years) indicating monthly precipitation. How to find values greater than the average of each column (month). The values of each column should be compared with the average data of each column and if it is greater print 1 instead of that value or else print 0 so we have a matrix with the same rows and columns with 0 or 1 value.

here is random data.

w= randi([1 12], 4,5)

w =

 1    12     1     8     9
 9     3    11     3    10
 8     2     8    12     1
 2     1     7     8    10

for example

result=
     0     1     0     1     1
     1     0     1     0     1
     1     0     1     1     0
     0     0     1     1     1

Solution

  • A = randi([1 5],4,6);
    [rows, columns] = size (A);
    for i = 1:columns
      for j =1:rows
       if  A(j,i) >= mean(A(:,i));
        P(j,i) = 1;
       else P(j,i)=0;
       end
      end
    end