BLKKROW
BLKKROW

Reputation: 23

Average of Elements in Array

So I am relatively new to MatLab and I was assigned the task to find the average of all of the elements in the first or last rows and first or last columns in an array. My function is below:

function [ myavg ] = avg_outer( array_in )
%UNTITLED2 Summary of this function goes here
%   Detailed explanation goes here

[rowsin, colin]=size(array_in);
sum=0;
numelement=0;
currentpos=1;
currentrow=1;
j=1;
while currentpos>1 && currentpos<rowsin
    sum=sum+array_in(currentrow,1)+array_in(currentrow,colin);
    numelement=numelement+2;
    currentrow=currentrow+1;
    if currentrow==1
        for j=1:1:colin
            sum=sum+array_in(currentrow,j);
            numelement=numelement+1;
        end
    elseif currentrow==rowsin
                sum=sum+array_in(currentrow,j);
                numelement=numelement+1;
    end
end
    myavg=sum/numelement;
end

When I run the function with a random array, I am not getting a result.

Any help or idea on where I went wrong?

Upvotes: 2

Views: 112

Answers (2)

Phil Goddard
Phil Goddard

Reputation: 10782

The right way to do this is as per the answer from @kmac. But specifically related to your looping code, there are multiple issues.

  1. currentpos starts at 1, which means that the while loop is never entered because currentpos > 1 is false. This is why you are getting NaN as the answer.
  2. Even after fixing the above, you never increment currentpos so the while loop would never be exited (or more correctly would execute until an out of bounds error occurs).
  3. Even after fixing the above, the first time into the while loop (in the 3rd line of the loop) you make currentrow = currentrow + 1;, which will be 2, means that the subsequent if statement is always false, and you will not be summing the first row of the matrix.
  4. Even if you fix the above, the for loop adds all elements of the first row, but you've already accounted for the first and last elements of this row, so you're adding them into the sum twice.
  5. Even if you fix the above, when currentrow == rowsin, i.e. the last row, you don't have a for loop to do the actual summation of the elements of the row. Noting that you don't want the first and last element because you've already added them in.

Upvotes: 1

kmac
kmac

Reputation: 698

Assuming I read the problem statement correctly, you can just create a mask that is true around the border, false in the middle, and take the mean of the masked version of A.

function [out_avg] = avg_outer(A)
  mask = true(size(A));
  mask(2:end-1,2:end-1) = false;
  out_avg = mean(A(mask));

I couldn't really follow the logic in your posted code to debug it, sorry. Hopefully this answer shows you some of the advantages of vectorizing Matlab code.

Upvotes: 1

Related Questions