How to use 'Switch case' with Matlab Function Block in Simulink?

조회 수: 15 (최근 30일)
Harshil Patel
Harshil Patel 2015년 6월 26일
편집: cqut 2018년 5월 2일
I'm able to run the following code in MATLAB:
n = input('n: ');
x = 3;
y = 2;
switch n
case 1
z = (x-y)/2
case 2
z = (x+y)/2
end
I want the 'n' value to come from a constant (or any other input block), which goes to MATLAB Function Block, and display the output when I simulate the Simulink model. Something like this:
I edited the Function Block's code as follows:
function result = fcn(n)
%#codegen
x = 3;
y = 2;
switch n
case 1
z = (x-y)/2
case 2
z = (x+y)/2
end
Its giving me several errors:
Can someone tell me what is wrong with my code or any other fixes to make this thing work?
Thanking You, Harshil

답변 (3개)

Azzi Abdelmalek
Azzi Abdelmalek 2015년 6월 26일
What if n is different from 1 and 2? Try this
function result = fcn(n)
%#codegen
x = 3;
y = 2;
z=0;
switch n
case 1
z = (x-y)/2
case 2
z = (x+y)/2
end
  댓글 수: 3
Azzi Abdelmalek
Azzi Abdelmalek 2015년 6월 26일
I tested this code, it works fine. Post your real code, we can't find the problem with another code.
Harshil Patel
Harshil Patel 2015년 6월 28일
Mr. Azzi, The real code just has more variables and multiple outputs within the 'cases'. So I simplified the problem for myself to see if it works or not. Still no improvement. I tried the exact code which you posted but Simulink did not give me an output, just errors. Do I need any additional compiler? (I already have the SDK, which lets me use and simulate Matlab function blocks for general purposes). I just want the function block to take the value 1 or 2 from a 'constant' block, and display the output '0.5' or '2.5' (depending on the case) in a 'display' block, when I simulate the model in Simulink.
Thanking you, Harshil

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


Anjum Tamboli
Anjum Tamboli 2017년 11월 30일
</matlabcentral/answers/uploaded_files/96734/Screenshot%20(29).png>This code does not work. for first range of values output should be only at y and for second range ouput should be at y1. please suggest me the modifications to run the program successfully. Thanks and Regards Anjum

cqut
cqut 2018년 5월 2일
편집: cqut 2018년 5월 2일
you missed otherwise + statement,you can try this:
function result = fcn(n)
%#codegen
x = 3;
y = 2;
switch n
case 1
z = (x-y)/2
case 2
z = (x+y)/2
otherwise
z = ??
end

카테고리

Help CenterFile Exchange에서 Simulink Functions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by