Hello, could you please help me? Thank you so much. (Matlab) - using matlab prog
ID: 3109799 • Letter: H
Question
Hello, could you please help me?
Thank you so much.
(Matlab) - using matlab program
4. Use a while loop to sum up the elements of a vector (starting with the first element) until the sum is bigger than 15. Print out a message if the sum never gets bigger than 15. Otherwise, print out the sum. Both print statements should happen AFTER the loop has finished. Test the while loop with x [1.7 6.2 3.4 10.5 9.1] and x I-56 2.20.1 -10 12]. Hint: A simple way to swap from one x to the other is to declare both assignments and just comment one out. Then you can demonstrate both to the TA without having to make a copy of the while loop. eg %x F[1.7 6.2 3.4 10.5 9.1]; x C-5 6 2.2 0.1 -10 12] Hint: You will need an index variable to tell if you've gone past the end of the array. Self-check 1.7000 6.2000 3.4000 10.5000 9.1000 Partial sum of elements of x is 21.800000 sum (x) ans 30.9000 fr -5.0000 6.0000 2.2000 0.1000 10.0000 12.0000 Partial sum is not bigger than 14.00, it is 5.300000 sum (x) ans 5.3000Explanation / Answer
MATLAB CODE:
clc
clear all
%x=[1.7 6.2 3.4 10.5 9.1];
x=[-5 6 2.2 0.1 -10 12];
n=length(x); %stores the size of the vector
i=1; %loop counter
s=0; %initial sum declaration
while(i<=n) %loop condtion
s=s+x(i); %sum gets added up here
if(s>15) %checks if sum is above 15
break; %enters here if the condition is satisfied and breaks away from the loop
end
end
f='The partial sum is %4.2f '; %print statement in matlab similar to C
g='The partial sum is not greater than 15 and is %4.2f';
if(s>15)
fprintf(f,s);
else
fprintf(g,s);
end
sum(x)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.