Creating a function

Question 1 Create a function called f that satisfies the following criteria: For values of x>2, f(x)=x^2 For values of x<=2, f(x)=2x Plot your results for values of x from -3 to 5. Choose your spacing to create a smooth curve.
Question 2 Create a function called g that satisfies the following criteria: For x<-pi, g(x)=-1 For x>=-pi and x<=pi, g(x)=cos(x) For x>pi, g(x)= -1 Plot your results for values of x from -2pi to 2pi. Choose your spacing to create a smooth curve.

2 个评论

Asking homework questions is frowned upon.
show us that you made some effort in order to do it and we might help

请先登录,再进行评论。

回答(2 个)

1. Do you think that copying and pasting a few obvious homework problems will get much of a positive response? From your post it is not obvious whether you are a spam robot or a living human being, except that spam robots probably would be programmed to imitate human interaction better than that.
2. Most participants here expect a minimal of effort on the part of the asker. So show what you have tried, where you are stuck, and ask a specific MATLAB question. It is very likely that you will get good help this way.
EDIT
O.k., now we can get somewhere. IF statements do not pick out array elements like you are thinking they do. I would use logical indexing for question 1. Here is an example for you to play with. It doesn't solve your problem, but will teach you some things to solve it. Copy and paste these lines, then read and think about the output.
x = 0:.5:3
y = zeros(1,length(x))
idx1 = x>1
idx2 = x<=1
x(idx1)
y(idx1)
x(idx2)
y(idx2)
x(idx2).^2
For the rest, look in the documentation for the keyword function.

2 个评论

I apologize for not showing any effort in the problems that I asked for help on. On question 1 I have put:
if x>2
y=x^2
elseif x<=2
y=2.*x
end
x= -3:1:5;
I get ??? undefined function or variable 'x' and an error in if x>2 and I do not know where to go from there.
"Create a function" means, that you should create a function. Look in the documentation for a description: "doc function". You define the variable x *after* using it - it must be available *before*.

请先登录,再进行评论。

Walter Roberson
Walter Roberson 2011-4-3

0 个投票

f := @(x) (-2*x*sin((x>2)-1)+x^2*sin(x>2))/sin(1);
By the time you figure out why that works, you should be well prepared to handle the second part.
I would, by the way, not recommend submitting this answer for your assignment: you are going to have to document why it works and how you created such an odd expression.

类别

帮助中心File Exchange 中查找有关 Matrix Indexing 的更多信息

产品

提问:

2011-4-3

Community Treasure Hunt

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

Start Hunting!

Translated by