Switch does not work in GUI

조회 수: 3 (최근 30일)
Lawson Hoover
Lawson Hoover 2012년 11월 9일
While running my code through a GUI the SWITCH function does that detect the cases, or maybe it just jumps to the bottom otherwise every time.
contents = cellstr(get(S.element,'String'));
t1 = contents{get(S.element,'Value')};
t = char(t1);
contents = cellstr(get(S.mass,'String'));
u1 = contents{get(S.mass,'Value')};
u = char(u1);
contents = cellstr(get(S.volume,'String'));
v1 = contents{get(S.volume,'Value')};
v = char(v1);
global dens
switch t
case strcmp(t,'Scandium')
dens = 2.989;
case strcmp(t,'Yttrium')
dens = 4.469;
case strcmp(t,'Selenium')
dens = 4.809;
case strcmp(t,'Krypton')
dens = .003733;
case strcmp(t,'Neodymium')
dens = 7.007;
case strcmp(t,'Antimony')
dens = 6.685;
case strcmp(t,'Astatine')
dens = 7;
otherwise
dens = 8.55;
end
Every time it jumps to the other wise option of -- dens = 8.55.

채택된 답변

Walter Roberson
Walter Roberson 2012년 11월 9일
You need to convert
switch t
to
switch true
because the value that you give in the "switch" is compared to the values of the "case" statements, and the values of the case statements are the result of the strcmp() and hence are true or false.
Alternately, leave it as "switch t" and remove the strcmp()
case 'Yttrium'
  댓글 수: 1
Walter Roberson
Walter Roberson 2012년 11월 10일
편집: Walter Roberson 2012년 11월 10일
Consider this:
densities = struct('scandium', 2.989', 'yttrium', 4.469, 'selenium', 4.809);
tl = lower(t);
if isfield(densities,tl)
dens = densities.(tl);
else
error('not a known element')
end

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Image Analyst
Image Analyst 2012년 11월 10일
Try it like this:
switch lower(t)
case 'scandium'
dens = 2.989;
case 'yttrium'
dens = 4.469;
case 'selenium'
dens = 4.809;
case 'krypton'
dens = .003733;
case 'neodymium'
dens = 7.007;
case 'antimony'
dens = 6.685;
case 'astatine'
dens = 7;
otherwise
dens = 8.55;
end

Lawson Hoover
Lawson Hoover 2012년 11월 11일
Thank you for the help, I had forgotten that STRCMP returns a true or false. I made the adjustments to the code and now it works! Thanks again!

카테고리

Help CenterFile Exchange에서 Dialog Boxes에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by