Creating a function

조회 수: 11 (최근 30일)
Jeff Cox
Jeff Cox 2011년 4월 3일
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
Petter
Petter 2011년 4월 3일
Asking homework questions is frowned upon.
Paulo Silva
Paulo Silva 2011년 4월 3일
show us that you made some effort in order to do it and we might help

댓글을 달려면 로그인하십시오.

답변 (2개)

Matt Fig
Matt Fig 2011년 4월 3일
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
Jeff Cox
Jeff Cox 2011년 4월 3일
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.
Jan
Jan 2011년 4월 3일
"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일
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.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by