How to solve this without goto statement?

1 回表示 (過去 30 日間)
Amit Kumar
Amit Kumar 2014 年 5 月 16 日
コメント済み: Amit Kumar 2014 年 5 月 16 日
Hi all, I think it is bad that matlab doesn't have a goto statement (many people will strongly disagree, but excuse me for the same). I am not a great programmer and I do not know what alternative should be used in the following script:
m1=2140.67;
m2=0.2*m1;
F=440;
k1=0.7*1e6;
w1=sqrt(k1/m1);
c1=10; c2=0; c3=0;
for(k2=1e3:1:1e5)
for (w=18:1e-4:18.1)
x1 = 1/(((-m1*w^2+k1+k2)*(-m2*w^2+k2) - k2^2))*k2*F*1;
% if(abs(x1)>0.0025)
% { goto abc}
if(abs(x1)<c1 && abs(x1)<(0.0025))
c1=x1;
c3=k2;
else
end
end
%abc:
%continue;
end
fprintf('val : x1 = %4.6f m and k2 = %4.6f N/m \n',c1,c3);
There are 2 for loops in this script. I wish that for any value of w, if (abs(x1)>0.0025), the next iteration should begin in outer loop (not the loop of w, so 'continue' is not useful). So what should I do to get next iteration of outer loop i.e. next iteration of k? Had matlab been using goto, I could have employed what is given in % (comments).

採用された回答

Image Analyst
Image Analyst 2014 年 5 月 16 日
編集済み: Image Analyst 2014 年 5 月 16 日
I don't see a loop over k, just k2. But when that condition happens, put a break in the inner loop
if (abs(x1)>0.0025)
break;
end
and then outside the inner loop but inside the outer k2 loop, put this:
if (abs(x1)>0.0025)
continue;
end
x1 will still have the same value so that should work.
  2 件のコメント
Image Analyst
Image Analyst 2014 年 5 月 16 日
Haven't heard from you so perhaps you need it spelled out exactly. See below:
clc;
workspace;
m1=2140.67;
m2=0.2*m1;
F=440;
k1=0.7*1e6;
w1=sqrt(k1/m1);
c1=10;
c2=0;
c3=0;
tic;
for k2 = 1e3 : 1e5
for w = 18 : 1e-4 : 18.1
x1 = 1/(((-m1*w^2+k1+k2)*(-m2*w^2+k2) - k2^2))*k2*F*1;
if abs(x1) > 0.0025
break;
end
if (abs(x1) < c1 && abs(x1) < (0.0025))
c1=x1;
c3=k2;
end
end
if abs(x1) > 0.0025
continue;
end
end
toc
fprintf('val : x1 = %4.6f m and k2 = %4.6f N/m \n',c1,c3);
I cleaned up a few other things too.
Amit Kumar
Amit Kumar 2014 年 5 月 16 日
Thanks a lot!

サインインしてコメントする。

その他の回答 (2 件)

the cyclist
the cyclist 2014 年 5 月 16 日
I am not 100% I understand the logic you are trying to implement, but I think you want the break command.

Brian B
Brian B 2014 年 5 月 16 日
for(k2=1e3:1:1e5)
for (w=18:1e-4:18.1)
x1 = 1/(((-m1*w^2+k1+k2)*(-m2*w^2+k2) - k2^2))*k2*F*1;
if(abs(x1)>0.0025)
break;
elseif(abs(x1)<c1 && abs(x1)<(0.0025))
c1=x1;
c3=k2;
end
end
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by