using x vector input to find corresponding y value

조회 수: 15 (최근 30일)
Vincent
Vincent 2022년 12월 11일
편집: Torsten 2022년 12월 11일
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