Multiple switch cases for different operations
8 views (last 30 days)
Show older comments
Hi all, I want to do 3 processes. At first time i want to do some arithmetic operations which i can do it using switch cases.. After calculating i want to do another operation, for that i need to use first operation value. In third operation, again i have multiple case from that i have to choose what ever i want for that i want to use my second operation values...
If anyone know, pls suggest me too..
I tried this but i dint get the answer..
clear; clc; n=input('Please enter the figure:','s'); switch n case ('triangle'); n=3; sum=(n-1).*(180); case ('square'); n=4; sum=(n-1).*(180); case('pentagon'); n=5; sum=(n-2).*(180); case ('hexagon'); n=6; sum=(n-3).*(180); result=sum; end
result=input('Please enter the figure:','s'); switch result case('add'); addition=result+100; case('mul'); multn=result.*1; end
Anyother solutios (apart from switch case) also Welcome!
Thanks in advance.
1 Comment
Accepted Answer
dpb
on 1 May 2014
n=input('Please enter the figure:','s');
switch n
case ('triangle');
n=3;
sum=(n-1).*(180);
case ('square');
n=4;
sum=(n-1).*(180);
case('pentagon');
n=5;
sum=(n-2).*(180);
case ('hexagon');
n=6;
sum=(n-3).*(180);
result=sum;
end
result=input('Please enter the figure:','s');
switch result
case('add');
addition=result+100;
case('mul');
multn=result.*1;
end
You only saved result for the last case in the first switch block which is the variable you tried to use later. Put the statement
result=sum;
after the end of the block to make the assignment for each case. Or, better yet, since sum is not a descriptive variable name for those cases, anyway, replace
sum=...;
in each case by
result=...;
and dispense with the variable sum altogether. (Not to mention that by using sum as a variable you have aliased the builtin function sum which is used for + and much interesting behavior is sure to ensure. Don't do things like that!!! :) Of course, it's not necessarily easy to know as a Matlab newbie that there is a function sum since virtually always one use the '+' operator instead.
Then, your next problem is you duplicated the input text to ask for a figure again when instead you must have intended to ask for an arithmetic operation. So, you need to fix your prompt text. Then to compound the problem, you used the variable result that you just previously computed and want to use again as the target for that input thus overwriting it. Write something like
ops=input('Please enter the desired operation: (+,-)','s');
switch ops
...
Those should get you on your way...
More Answers (0)
See Also
Categories
Find more on Interactive Control and Callbacks in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!