Consider the function defined by g(x) =sin(πx), x ∈ (−1, 1] x^4 − 1, x ∈ [−1.5, −1] ∪ (1, 1.5] (a) Write a MATLAB function gxsin that takes as input a vector x, and returns a vector y that contains the corresponding values of the function g. (b) Using the function gxsin and a suitable array x containing 102 entries, write appropriate MATLAB commands that produce a plot of the function defoned above. The plot should be entitled "Plot of g(x) vs x". THIS IS WHAT I HAVE:
function y = gxsin(x)
for i=1:length(x)
if (x(i)> -1) && (x(i)<=1)
g(i)=sin(pi*x(i));
elseif (x(i)>=-1.5) && (x(i)<=-1)|| (x(i)>1) && (x(i)<=1.5)
g(i)= ((x.^4 -1));
end
end
end
x=linspace(-1.5,1.5,102);
y=gsxin(x), I'm getting an error when i type this part

 采纳的回答

madhan ravi
madhan ravi 2018-11-12
编辑:madhan ravi 2018-11-12
Make a note a loop is not needed to do this operation , logical indexing is better and efficient, you got error becuaw you didn't define gsxin(x) function like I did
LOGICAL INDEXING WAY
x=linspace(-1.5,1.5,102);
y=gsxin(x); %function calling
plot(x,y)
function g=gsxin(x) %function definition
id=(x> -1) & (x<=1);
g(id)=sin(pi*x(id));
id1=((x>=-1.5) & (x<=-1))| ((x>1) & (x<=1.5));
g(id1)= (x(id1).^4 -1);
end
LOOP WAY
x=linspace(-1.5,1.5,102);
y=gsxin(x); %function call
plot(x,y)
function g=gsxin(x) %function definition
g=zeros(1,numel(x)); %pre-allocation
for i =1:numel(x)
if (x(i)> -1) && (x(i)<=1)
g(i)=sin(pi*x(i));
elseif (x(i)>=-1.5) && (x(i)<=-1)|| (x(i)>1) && (x(i)<=1.5)
g(i)= (x(i).^4 -1);
end
end
end

3 个评论

Tawanda Le Bourne
Tawanda Le Bourne 2018-11-12
编辑:madhan ravi 2018-11-12
thank you, i found my error
madhan ravi's reply : Anytime :)
Tawanda Le Bourne
Tawanda Le Bourne 2018-11-12
编辑:madhan ravi 2018-11-12
Can you help me with this one please.
Consider the sequence defined by xn+1 = xn − tan(xn) for some initial value x0. (a) Write a MATLAB function seqtan that takes the values x0 and etol as inputs, and calculates the terms of the sequence above until the stopping criterion xn+1 − xn/|xn+1|< etol is satisfied. The function should output the final calculated term of the sequence and store the value as x.
(b) Write a MATLAB command that executes seqtan with x0 = 8 and etol = 2 × 10^−10 and stores the resulting output as u.
I DON'T UNDERSTAND THIS ONE
madhan ravi's reply : post a separate question by providing all the necessary details
THIS IS WHAT I DID function x= seqtan(x0,etol)
x=1;
y=x-tan(x);
x=y;
while delta > etol
y=x-tan(x);
delta=abs(y-x)
x=y;
end

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by