switch case construction help

21 Ansichten (letzte 30 Tage)
Ajay
Ajay am 8 Okt. 2012
(Ajay deleted the question so I (MF) am restoring it as best I can.)
I wrote this body of code:
function output = InteriorAngle(input)
switch input (InteriorAngle)
case 'triangle'
disp ('180')
case 'square'
disp ('360');
case 'pentagon'
disp ('540');
case 'hexagon'
disp ('720');
case 'heptagon'
disp ('900');
case 'octagon'
disp ('1080');
case 'nonagon'
disp ('1260');
case 'decagon'
disp ('1440');
otherwise
disp ('0');
end
end
but for some reason, it's not running when i input,
in = cell(1,3);
in{1,1} = 'triangle';
in{1,2} = 'hexagon';
in{1,3} = 'dodecagon';
out = InteriorAngle(in)
what am i doing wrong?
  8 Kommentare
Walter Roberson
Walter Roberson am 8 Okt. 2012
Question content has been edited out of existence by the original poster :(
Matt Fig
Matt Fig am 9 Okt. 2012
Saved from google cache:
I wrote this body of code:
function output = InteriorAngle(input)
switch input (InteriorAngle)
case 'triangle'
disp ('180')
case 'square'
disp ('360');
case 'pentagon'
disp ('540');
case 'hexagon'
disp ('720');
case 'heptagon'
disp ('900');
case 'octagon'
disp ('1080');
case 'nonagon'
disp ('1260');
case 'decagon'
disp ('1440');
otherwise
disp ('0');
end
end
but for some reason, it's not running when i input,
in = cell(1,3);
in{1,1} = 'triangle';
in{1,2} = 'hexagon';
in{1,3} = 'dodecagon';
out = InteriorAngle(in)
what am i doing wrong?

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Matt Fig
Matt Fig am 8 Okt. 2012
Bearbeitet: Matt Fig am 8 Okt. 2012
You are recursively calling the function from inside the function with no way to terminate the recursion. Additionally, you have named a variable the same name as a MATLAB function (INPUT). In general, you should avoid this practice as it masks the function.
Once you take care of these problems, put your switch inside a FOR loop that loops over the length of the input argument. You switch on IN{ii}.
  4 Kommentare
Ajay
Ajay am 8 Okt. 2012
function output = InteriorAngle(input)
for s=1:8,
switch input ('s')
case 'triangle'
disp ('180')
case 'square'
disp ('360');
case 'pentagon'
disp ('540');
case 'hexagon'
disp ('720');
case 'heptagon'
disp ('900');
case 'octagon'
disp ('1080');
case 'nonagon'
disp ('1260');
case 'decagon'
disp ('1440');
otherwise
disp ('0');
end
end
end
Matt Fig
Matt Fig am 8 Okt. 2012
Why is s always 1-through-8? What if the length of input is only 3 as in your example?
for ii = 1:length(IN)
switch IN{ii}

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Ajay
Ajay am 8 Okt. 2012
it worked and i get it, thanks!

Kategorien

Mehr zu Performance and Memory finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by