A vector is given by: x=[15 -6 0 8 -2 5 4 -10 0.5 3]. Usingconditional statement
ID: 3616905 • Letter: A
Question
A vector is given by: x=[15 -6 0 8 -2 5 4 -10 0.5 3]. Usingconditional statements and loops, write a program that determinesand displays the sum of the positive elements of the vector, andthe sum of the negative elements of the vector.I know that I need to use for-end loops and if-elsestatements, but I can't figure out how to put it alltogether.
A vector is given by: x=[15 -6 0 8 -2 5 4 -10 0.5 3]. Usingconditional statements and loops, write a program that determinesand displays the sum of the positive elements of the vector, andthe sum of the negative elements of the vector.
I know that I need to use for-end loops and if-elsestatements, but I can't figure out how to put it alltogether.
Explanation / Answer
x=[15 -6 0 8 -2 5 4 -10 0.5 3]; % Initialize sum of positive and negativevalues SumPositive = 0; SumNegative = 0; PositiveNumbers = []; NegativeNumbers = []'; for i=1:length(x) if x(i) < 0 SumNegative = SumNegative + 1; NegativeNumbers(SumNegative)=x(i); end if x(i) > 0 SumPositive =SumPositive +1; PositiveNumbers(SumPositive)=x(i) ; end end; % Results PositiveNumbers SumPositive NegativeNumbers SumNegativeRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.