using x vector input to find corresponding y value

17 次查看(过去 30 天)
I am trying to find the corresponding y values to a x vector, which is x=[-2:0.5:16.5], but my code is not giving me back a list of y values. It is just displaying that y =0
Here's my code:
function findingy = findingy(x)
if x>=0 && x<=2.5
y=2*x;
elseif x>=2.5 && x<=7
y=5;
elseif x>=7 && x<14.5
y = 9.6667-0.6667*x;
else y=0
end

回答(1 个)

Torsten
Torsten 2022-12-11
编辑:Torsten 2022-12-11
Three possible solutions:
x = [-2:0.5:16.5];
y = findingy1(x);
figure(1)
plot(x,y)
y = findingy2(x);
figure(2)
plot(x,y)
y = arrayfun(@(i)findingy3(x(i)),1:numel(x));
figure(3)
plot(x,y)
function y = findingy1(x)
y = zeros(size(x));
y(x>=0 & x<=2.5) = 2*x(x>=0 & x<=2.5);
y(x>=2.5 & x<=7) = 5;
y(x>=7 & x<14.5) = 9.6667-0.6667*x(x>=7 & x<14.5);
end
function Y = findingy2(X)
Y = zeros(size(X));
for i = 1:numel(X)
x = X(i);
if x>=0 && x<=2.5
y=2*x;
elseif x>=2.5 && x<=7
y=5;
elseif x>=7 && x<14.5
y = 9.6667-0.6667*x;
else
y=0;
end
Y(i) = y;
end
end
function y = findingy3(x)
if x>=0 && x<=2.5
y=2*x;
elseif x>=2.5 && x<=7
y=5;
elseif x>=7 && x<14.5
y = 9.6667-0.6667*x;
else
y = 0;
end
end

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by