for loop or while loop?

2 次查看(过去 30 天)
Maria Chu
Maria Chu 2015-6-9
评论: dpb 2015-6-10
hi i need to write a program, but i dont know how to programming. I need to find a length l (l>0) so this way b1 and b2 are equal. b1 and b2 are functions dependent of l(variable) p,w,e,t are values that i already have. I need to iterate using increments of 0.001 and display l and b1. Please help me! :(
e=1800, t=120
First case: p=1000, w=0
Second case: p=0, w=12.5
Third case: p=500, w=12.5
p=input('point load: ') ;
w=input (' distributed load: ') ;
e=input (' normal stress: ');
t=input ('shear stress: ');
syms l b1 b2
for l=0:100000
l=l+0.001
b1= ((3*(p*l+0.5*w*l*l))/(32*e))^(1/3);
b2 =((3*(p+w*l))/(16*t))^(1/2);
if b1==b2
display l
display b1
display b2
end
end

采纳的回答

dpb
dpb 2015-6-9
  1. Don't need syms unless you were to try to solve for a symbolic solution; to find a numeric solution it isn't of any use
  2. The loop construct in Matlab would be for l=0:deltaL:L
where deltaL is the increment and L the upper limit. Note, however, that there's no guarantee that at the resolution there would be an exact solution, you would want to write the if as
if abs(b1-b2)<e
where e is an error of convergence. Even here, you really don't know that you're going to be close enough to any arbitrary solution so robustness would be to test for a change in sign of the difference which then gives you a bounding location.
But, in Matlab, the way to do things like this is to use fzero
Write
>> e=1800; t=120;
>> p=1000; w=0;
>> f= @(l) ((3*(p*l+0.5*w*l*l))/(32*e))^(1/3)-((3*(p+w*l))/(16*t))^(1/2);
>> L1=fzero(f,50)
L1 =
37.5000
>>
In general, write the routine to
  1. read the input values that aren't constants
  2. set the anonymous function for those values
  3. call fzero() with that definition of the function
  4. repeat for cases as desired.
  2 个评论
Maria Chu
Maria Chu 2015-6-9
Thank you!! You saved me literally!
dpb
dpb 2015-6-10
While you've probably gone on to bigger/better things, :) I'll note that in the above sequence the alternative that's a little more in coding the function but makes it generic is to include the coefficients as additional arguments of the anonymous function; then the values in play at the time get passed into the evaluation rather than being hardcoded as above as the values in existence at the time the function is defined.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by