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

********* USE MATLAB *********** 1. Create a 20-element row vector comprised of

ID: 2293792 • Letter: #

Question

********* USE MATLAB ***********

1. Create a 20-element row vector comprised of random numbers between -10 and +10, then find the sum of all positive elements using each of the 3 following methods: 2. Use for-loop to find the sum of all the positive elements in the vector 3. Use for-loop to create a new vector comprised of all the positive elements from the original vector, and then find the sum of this new vector. 4. Use logical indexing instead of loops to find the positive elements in the original 20-element vector.

Explanation / Answer

MATLAB code is given below.

clc;
close all;
clear all;

% creating 20 element row vector x
x = floor(rand(1,20)*21-10);
% 2. Finding the sum of all positive values in x using for loop
summation1 = 0;
for k = 1:length(x)
if x(k) > 0
summation1 = summation1 + x(k);
end
end
display (summation1)

% 3. Finding the sum of all positive values in x using for loop and
% a new vector
for k = 1:length(x)
if x(k) > 0
y(k) = x(k);
end
end

summation2 = sum(y)

% 4. Finding the sum of all positive values in x using logical indexing
summation3 = sum(x(x> 0))

Result:

summation1 =

48


summation2 =

48


summation3 =

48