Switch Case with Loop
8 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Muhammad Syafiq Bin Salahudin
le 17 Août 2018
Commenté : Image Analyst
le 16 Avr 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 :)
0 commentaires
Réponse acceptée
KSSV
le 17 Août 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 commentaires
Lahiru Suraweera
le 16 Avr 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
le 16 Avr 2021
That's fine. It can take pure numbers, like doubles, for the values on a "case" line.
Plus de réponses (1)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!