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

 Réponse acceptée

madhan ravi
madhan ravi le 12 Nov 2018
Modifié(e) : madhan ravi le 12 Nov 2018

0 votes

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 commentaires

Tawanda Le Bourne
Tawanda Le Bourne le 12 Nov 2018
Modifié(e) : madhan ravi le 12 Nov 2018
thank you, i found my error
madhan ravi's reply : Anytime :)
Tawanda Le Bourne
Tawanda Le Bourne le 12 Nov 2018
Modifié(e) : madhan ravi le 12 Nov 2018
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
Tawanda Le Bourne
Tawanda Le Bourne le 12 Nov 2018
Modifié(e) : Tawanda Le Bourne le 12 Nov 2018
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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by