using x vector input to find corresponding y value

14 ビュー (過去 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 Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by