How to find the sum of the resulting y's by using a function and if conditions?

1 visualización (últimos 30 días)
This is the code I made to give the values of y for the given x. It displays the correct values.
But everything I do to it to produce a sum of the all the y values chances the initial correct y values.
Is there a way to make it answer with the y values in an array so I can use the 'sum' function? or am I approaching this the wrong way?
I have not learned about using 'fprintf' and everything I find uses that particular function.
function [y] = Given(~)
% calculate the values of y for the following x:
% Find the sum of the all y
for x = [0 1 15 -7 88 -34 7]
if x <= 2
y = -2.*(x.^2);
elseif x < 25
y = x.*(x-4+3.*x.^3);
else
y = (x.^2)-81;
end
disp(y);
end

Respuestas (1)

Image Analyst
Image Analyst el 10 de Oct. de 2021
Not sure what you want to do but if you want a vector of all the y values and their sum, do
function [y, sumY] = Given(~)
% calculate the values of y for the following x:
% Find the sum of the all y
allX = [0 1 15 -7 88 -34 7]
for k = 1 : length(allX)
x = allX(k);
if x <= 2
y(k) = -2.*(x.^2);
elseif x < 25
y(k) = x.*(x-4+3.*x.^3);
else
y(k) = (x.^2)-81;
end
sumY = sum(y(1:k));
fprintf('At end of iteration %d, y = %d and the sum = %f.\n', k, y(k), sumY)
end
You get
At end of iteration 1, y = 0 and the sum = 0.000000.
At end of iteration 2, y = -2 and the sum = -2.000000.
At end of iteration 3, y = 152040 and the sum = 152038.000000.
At end of iteration 4, y = -98 and the sum = 151940.000000.
At end of iteration 5, y = 7663 and the sum = 159603.000000.
At end of iteration 6, y = -2312 and the sum = 157291.000000.
At end of iteration 7, y = 7224 and the sum = 164515.000000.

Categorías

Más información sobre Programming en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by