In: Computer Science
MATLAB, if-else
Write a script which to do the following. Take an array of any size as input and check if all the elements are integers. (i) If not, display the error message ‘Invalid input!’. Use the error command to create a proper error message in red. (ii) If yes, count the number of rows where the sum of the elements is smaller than the average row sum. It is recommended that you use a test variable with many rows (> 10 ).
Case 1 :
When the matrix contains elements that are not integers
MATLAB code :
A = rand(11,11)
[rows,columns] = size(A);
row_sum = sum(A,2);
total = sum(row_sum);
avg_row_sum = total / rows;
count = 0;
for i = 1:rows
sum = 0;
for j = 1:columns
if floor(A(i,j)) ~=
A(i,j)
error('Invalid Input')
return
else
sum = sum + A(i,j);
end
end
if sum < avg_row_sum
count = count + 1;
end
end
disp(['The number of rows with sum smaller than average is : ',
num2str(count)])
Output :
.
Case 2 :
When the matrix contains elements that are integers
MATLAB code :
A = randi([1,10],[11,11])
[rows,columns] = size(A);
row_sum = sum(A,2);
total = sum(row_sum);
avg_row_sum = total / rows;
count = 0;
for i = 1:rows
sum = 0;
for j = 1:columns
if floor(A(i,j)) ~=
A(i,j)
error('Invalid Input')
return
else
sum = sum + A(i,j);
end
end
if sum < avg_row_sum
count = count + 1;
end
end
disp(['The number of rows with sum smaller than average is : ',
num2str(count)])
Output :
.
.