Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please write a MATLAB function that finds all positive entries in a matrix and t

ID: 3695019 • Letter: P

Question

Please write a MATLAB function that finds all positive entries in a matrix and their locations (i.e. row and column indices). Your function header should be: function [posentry, location] = findpositive (A) where the input A is a matrix; the first output posentry is a vector that contains all positive entries from A, and the second output location is a matrix with two columns, where the first column contains all the row indices and the second column contains all the column indices of those positive entries. For example, if your input matrix A = [3 -9 -2 -5 2 -1 0 4 2], the positive entries are: number 3 from row 1, column 1, number 2 from row 2, column 2, number 4 from row 2, column 3, number 2 from row 3, column 3. Your two outputs should be posentry = [3 2 4 2], and location = [1 2 2 3 1 2 3 3]. Please test the Matlab code on a couple of examples.

Explanation / Answer

function [posentry,location] = findPositive(A)
[rows cols] = size(A)

index = 1
for i = 1: rows
    for j = 1: cols
        if(A(i,j) >0)
            posentry(index, 1) = A(i,j)
          
            location(index, 1) = i
            location(index, 2) = j
            index = index+1
        end
    end
end
end
A = [1 2 -3; -2 4 -1; 6 -5 -2]
[posentry, location] = findPositive(A)

display(posentry)
display(location)

------------output--------------

1                                                                                                                       

   2                                                                                                                       

   4                                                                                                                       

   6                                                                                                                       

                                                                                                                           

   1   1                                                                                                                   

   1   2                                                                                                                   

   2   2                                                                                                                   

   3   1