MATLAB: Create a function to…

function 2 dimensioanl array input output sum negative positive loop if elseif for

Create a function *.m file that accepts a 2-dimensional array as a function input and has two function outputs. This function will use a nested loop to create one column vector that contains the sum of all the positive values in each row and another column vector that contains sum of all the negative numbers of each row. These two column vectors should be returned (sent back) to the function call.

Best Answer

It's not bad actually. The lines
positive=positive
negative-negative
are useless, and you want to create vectors of sums, not scalars. So one mistake is that you don't index variables positive and negative with the row index. To make it more efficient, you could even prealloc these variables: change
positive=0;
negative=0;
for
positive = zeros(size(x, 1));
negative = zeros(size(x, 1));
Another mistake is that k and j should go from 1 to the number of rows and columns of x. You can obtain them using function SIZE.