Write a MATLAB function
function [ AvgPos, AvgNeg ] = PosNegAverage ( X )
that calculates average of positive, AvgPos, and negative, AvgNeg, elements of array X, using the for‐end loop and if‐elseif‐else‐end selection structure. Do not use build‐in MATLAN functions in calculations. Apply the developed function for the following vector
X = [ ‐7, 1, 0, 0, 12, 6, 33.2, ‐7.5 ];
MATLAB Code:
close all
clear
clc
X = [-7, 1, 0, 0, 12, 6, 33.2, -7.5];
[AvgPos,AvgNeg] = PosNegAverage(X)
function [AvgPos,AvgNeg] = PosNegAverage(X)
AvgPos = 0;
AvgNeg = 0;
NumPos = 0;
NumNeg = 0;
for i=1:length(X)
if X(i) > 0
AvgPos = AvgPos + X(i);
NumPos = NumPos + 1;
else
if X(i) < 0
AvgNeg = AvgNeg + X(i);
NumNeg = NumNeg + 1;
end
end
end
if NumPos > 0
AvgPos = AvgPos/NumPos;
end
if NumNeg > 0
AvgNeg = AvgNeg/NumNeg;
end
end
Output:
AvgPos =
13.0500
AvgNeg =
-7.2500
Get Answers For Free
Most questions answered within 1 hours.