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

Imagine that you are collecting measurements for stress testing materials. For e

ID: 3830745 • Letter: I

Question

Imagine that you are collecting measurements for stress testing materials. For each material sample, you collect n measurements. You have m samples, so all your measurements are stored in an m x n matrix. Sometimes, your sensor malfunctions and the measurement value is NaN or Inf. You only want to continue analysis on samples where you have a complete set of measurements, so you need to remove every row containing NaN or Inf. Write a function remove_rows(). The input to your function is an m by n matrix. For example M = [ 1 9 0 8; 7 2 NaN 13; 4 2 10 0; 1 Inf 14 7 ]; Your function should remove the rows containing NaN and Inf and return two values, the clean matrix and the row indices of the rows which were removed. For the above example, the correct return values would be M_clean = [ 1 9 0 8; 4 2 10 0; ]; rows_removed = [2, 4]; Note: You are required to use the programming method (loops, conditional statements). You are NOT allowed to use the built-in Matlab function *any*

Explanation / Answer

function [M_clean,rows_removed ] = remove_rows( M)
[m,n] = size(M);
M_clean = [];
rows_removed = [];
for i = 1:m
flag = 1; % asume row does not contain NaN or inf
for j = 1:n
if( M(i,j)== Inf || isnan(M(i,j))) % isnan return if a number is Nan or not
flag = 0;
break;
end
end
if(flag == 0) % malfunction row
rows_removed = [rows_removed i];
else
M_clean = [M_clean; M(i,:)];
end
end
end

OUTPUT

>> M = [ 1 9 0 8; 7 2 NaN 13; 4 2 10 0; 1 Inf 14 7 ];

[M_clean,removed_rows] = remove_rows(M);
>> M_clean

M_clean =

1 9 0 8
4 2 10 0;

>> removed_rows

removed_rows =

2 4