Switch-case force problem
이전 댓글 표시
I'm trying to write a code for using the switch-case structure to figure out the force needed to move an object for each case where the coefficient of friction is
metal on metal: u=0.2
wood on wood: u=0.35
metal on wood: u=0.40
rubber on concrete: u=0.70
w: the user inputs any weight
m: the different u values of each case
I'm am trying to print each force value of w*u for each case and then end the code. This is what I have right now, can I get a hand on how to fix the code?
for w=input('enter weight of object',s)
m = input('static friction coefficient',s);
switch m
case u == 0.2;
f=u*w;
case u == 0.35;
f=u*w;
case u == 0.40;
f=u*w;
case u == 0.70;
f=u*w;
end
end
댓글 수: 3
Walter Roberson
2021년 3월 24일
for w=input('enter weight of object',s)
You appear to be expecting multiple inputs as w, as otherwise you would not use a for loop. But you overwrite all of f each iteration. Perhaps you should not use for?
w=input('enter weight of object',s)
The only acceptable second input to input is the string "s" or character vector 's'. But if your variable s holds one of those then your w would not be numeric.
Aiden Estle
2021년 3월 24일
편집: Aiden Estle
2021년 3월 24일
Walter Roberson
2021년 3월 24일
u=2; for m=1:2;switch m; case u==1; disp('m1'); case u==2; disp('m2'); otherwise disp('m??') ; end;end
m2 m??
u=2; for m='12';switch m; case u==1; disp('m1'); case u==2; disp('m2'); otherwise disp('m??'); end;end
m?? m??
Why does the string execute twice instead of once (answer: '12' is a vector of values and for executes once per value)
Why does m=1 lead to m2 being displayed and m=2 lead to m?? being displayed?
Consider m=1 then switch m causes m (1) to be compared to u==1 first. u=2 so u==1 is false which is 0. Is m (1) equal to false (0)? No. So the first case is not matched. Second case is u==2 which is true. m is 1 and 1 equals true so the case is taken and m2 is printed.
Consider m=2. u== some value is 0 (false) or 1 (true) and neither of those can equal m which is 2, so you take the otherwise.
Now let m='1'. '1' is the character 1 and when you compare characters (switch) to numbers (0 or 1, false or true), then the character position in Unicode is used, and the character position for '1' is 49. But 49 never compares equal to 0 or 1.
답변 (1개)
Image Analyst
2022년 5월 28일
0 개 추천
If you want ranges for u personally I'd use an if/else, though you can use switch if you make the conditions correctly. But don't compare u to exact numbers with equals signs. Why not? Read the FAQ:
카테고리
도움말 센터 및 File Exchange에서 Programming에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!