Switch Case with Loop
조회 수: 7 (최근 30일)
이전 댓글 표시
Hi!
I need help with this code:
clc;
clear;
close all;
a=input('Enter the real value of load impedance ZL, a=');
b=input('Enter the Imagninary value of load impedance ZL, b=');
ZL=a+1i*b;
disp(['ZL=',num2str(ZL),'ohm']);
a1=input('Enter the real value of characteristic Impedance Z0, a1=');
b1=input('Enter the imaginary value of characteristic Impedance Z0, b1=');
Z0=a1+1i*b1;
disp(['Z0=',num2str(Z0),'ohm']);
disp('Enter the R- To determine the Voltage reflection coefficient');
disp('Enter the V- To determine the VSWR');
disp('Enter the Z- to determine the impedance Zx from load');
c=input('Enter your choice','s');
switch c
case 'R'
rc=(ZL-Z0)/(ZL+Z0);
x=real(rc);
y=imag(rc);
q=sqrt(x^2+y^2);
VSWR=(1+q)/(1-q);
disp(['The VSWR is',num2str(VSWR)]);
case 'Z'
zx=Z0*((ZL+1i*Z0*tan((2*pi)*0.35))/(Z0+1i*ZL*tan((2*pi)*0.35)));
disp(['The Zx from load ZL is ',num2str(zx),'ohm']);
otherwise
error('invalid choice');
end
I do not wish for the program to just end with an 'Invalid Choice' statement. I would like to program to loop back automatically prompting me to re-enter the parameters starting from Line 4. I am unsure on how to use syntaxes such as "if-else" or "for" or "while" to execute this. Please help!! Thank you :)
댓글 수: 0
채택된 답변
KSSV
2018년 8월 17일
c=input('Enter your choice','s');
while ~any(strcmp(c,{'R' 'Z'}))
c=input('Enter your choice','s') ;
end
switch c
case 'R'
rc=(ZL-Z0)/(ZL+Z0);
x=real(rc);
y=imag(rc);
q=sqrt(x^2+y^2);
VSWR=(1+q)/(1-q);
disp(['The VSWR is',num2str(VSWR)]);
case 'Z'
zx=Z0*((ZL+1i*Z0*tan((2*pi)*0.35))/(Z0+1i*ZL*tan((2*pi)*0.35)));
disp(['The Zx from load ZL is ',num2str(zx),'ohm']);
end
댓글 수: 2
Lahiru Suraweera
2021년 4월 16일
hi.
what about a switch statement with numerical cases. i only want input between 1 and 12 to be accepted.
c = input('Please enter the number of the conversion required: ');
switch (c)
case 1
whatever the program must do
case 2
whatever the program must do
...
case 12
whatever the program must do
otherwise
disp('invalid choice')
end
Image Analyst
2021년 4월 16일
That's fine. It can take pure numbers, like doubles, for the values on a "case" line.
추가 답변 (1개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!