Switch Case with Loop

15 views (last 30 days)
Muhammad Syafiq Bin Salahudin
Commented: Image Analyst on 16 Apr 2021
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 :)

Accepted Answer

KSSV
KSSV on 17 Aug 2018
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 Comments
Lahiru Suraweera
Lahiru Suraweera on 16 Apr 2021
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
Image Analyst on 16 Apr 2021
That's fine. It can take pure numbers, like doubles, for the values on a "case" line.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 17 Aug 2018
You might want to look at the menu() function.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!