フィルターのクリア

Function Call not working properly

1 回表示 (過去 30 日間)
Daniel Schilling
Daniel Schilling 2018 年 10 月 18 日
コメント済み: Kevin Chng 2018 年 10 月 18 日
t = linspace(-10,15,26);
plot(t, x_general(t))
where x_general is defined as:
function [x_out] = x_general(x_in)
if x_in >= -5 & x_in < 5
x_out = -2 .* abs(x_in) + 10
elseif x_in > 5 & x_in <= 10
x_out = 10
else
x_out = 0
end
end
When I run this, my plot comes up blank. Not sure why this happens?

回答 (2 件)

Stephen23
Stephen23 2018 年 10 月 18 日
編集済み: Stephen23 2018 年 10 月 18 日
You probably want to be using logical indexing rather than if:
function y = fun(x)
y = zeros(size(x));
idx = x>5 & x<=10;
y(idx) = 10;
idx = x>=-5 & x<5;
y(idx) = -2 .* abs(x(idx)) + 10
end
  2 件のコメント
Daniel Schilling
Daniel Schilling 2018 年 10 月 18 日
What do you mean?
Stephen23
Stephen23 2018 年 10 月 18 日
編集済み: Stephen23 2018 年 10 月 18 日
"What do you mean?"
The introductory tutorials teach the basic concepts, such as what indexing is, that you will need to know if you want to use MATLAB:
The point is that if does not apply to parts of an array, as you are trying to use it. But you can easily use logical indexing to specify parts of an array, and my answer shows you how.

サインインしてコメントする。


Kevin Chng
Kevin Chng 2018 年 10 月 18 日
t = linspace(-10,15,26);
plot(t, x_general(t))
function [x_out] = x_general(x_in)
x_out = zeros(1,length(x_in));
x_out(x_in >= -5 & x_in < 5) = -2 .* abs(x_in(x_in >= -5 & x_in < 5 )) + 10 ;
x_out(x_in > 5 & x_in <= 10) = 10 ;
end
In yor code, you are not returning the array, you return a single variable which is 0.
  4 件のコメント
Daniel Schilling
Daniel Schilling 2018 年 10 月 18 日
%Sets the interval for the sinc function
t = linspace(-2*pi,2*pi);
%Plots sinc using the built in function call
plot(t,sinc(t))
hold on
%Plots sinc function with user made function called MySin
plot(t,MySinc(t));
hold on
%Defining function "MySinc"
function [sinc_out] = MySinc(sinc_in)
%Definition of sinc(x)
if sinc_in ~= 1.0
sinc_out = sin(sinc_in)./sinc_in;
else
sinc_out = 0
end
end
So how come this one worked but without indexing perfectly fine but the one I asked the question about didnt? What's the difference?
Kevin Chng
Kevin Chng 2018 年 10 月 18 日
Because your condition
sinc_in ~= 0
All is true which is 1.
if any of them is 0, then your condition is false.then you are not allow enter the if.
That's why the code in your question enter else there which is x_out=0

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by