필터 지우기
필터 지우기

Switch/case command function

조회 수: 2 (최근 30일)
Angel Martinez
Angel Martinez 2012년 3월 28일
I'm trying to create a function with the switch /case commands and run it from another program satisfying certain criteria. The files are in the same folder but I'm not sure how to lay out the function and call it for that matter. Here is my function file:
function input = g(x) switch input case x < -pi disp('-1') case g >= -1 && g<= pi cos(g) case g > pi disp('-1')
end
Thanks for you help

채택된 답변

James
James 2012년 3월 28일
Here is the function that does it (hopefully it is what you want)
function y=g(x)
if x < -pi
y=-1;
elseif (x >= -pi && x<=pi)
y=cos(x);
elseif x > pi
y=-1;
end
  댓글 수: 2
Angel Martinez
Angel Martinez 2012년 3월 28일
Thank you. That makes sense.
James
James 2012년 3월 28일
No problem. It seems that you are asking two questions. For the layout of the function and calling from another program:
You can create the function by going to matlab,
1.File -> New-> function
2.Delete everything and paste the code in the code above.
3.Save it at the same folder as your calling program.
4.To use this g function from the main program, just type y=g(x) e.g. g(pi) at your main program function whenever you need to compute g(x).

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

추가 답변 (1개)

James
James 2012년 3월 28일
Hi Angel,
I'm not sure if I fully understand your problem. However, just a quick glance on it, the case statement is not possible for inequality. I guess you have to use a list of if-elseif :)
Extracted from http://www.mathworks.com/help/techdoc/ref/switch.html: A case_expression cannot include relational operators such as < or > to compare against the switch_expression. To test for inequality, use if-elseif statements.
  댓글 수: 1
Angel Martinez
Angel Martinez 2012년 3월 28일
Sorry about the vagueness. The problem is from Logical functions and selection structures. And the problem states:
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.
The plotting portion should be fairly easy but I guess I'm just confused with the creating the function since you call the function from the program and that's what i'm not sure hot to setup. sorry so long winded.

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

카테고리

Help CenterFile Exchange에서 Troubleshooting in Polyspace Products for Ada에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by