How to include a switch statement within a for loop?

7 ビュー (過去 30 日間)
Daniel Tanner
Daniel Tanner 2019 年 10 月 17 日
編集済み: Andrei Bobrov 2019 年 10 月 17 日
Hi, I am having to learn and apply for loops in my new job.
I have an equation which contains two variables each time, i.e. I have to compute at three different frequencies and at each of these frequencies there is a separate current. I have attached the code:
% Parameters
a_R = 0.0325;
a_T = 0.0325;
N_T = 164;
N_R = 10;
mu_0 = 4*pi*(10^-7);
f_Array = [10000,20000,40000];
w = 2*pi*f_Array; % Angular frequency
I = [2,1,0.5]; % Current
for i = 1:3
f = f_Array(i);
switch f
case 10000
I = 2;
case 20000
I = 1;
case 40000
I = 0.5;
end
K_R = ((mu_0^2)*(w(i)^2)*pi*N_T*N_R*(a_T^2)*(a_R^2)*I./(4*x_R_center));
end
Basically, the output I want is K_R at each frequency and respective curent, however the output just runs the first case and not the other two.
Any help would be greatly appreciated. Thanks.
  1 件のコメント
Adam
Adam 2019 年 10 月 17 日
編集済み: Adam 2019 年 10 月 17 日
At a glance,
K_R = ((mu_0^2)*(w(i)^2)*pi*N_T*N_R*(a_T^2)*(a_R^2)*I./(4*x_R_center));
should work on its own, removing the for loop. You have I in an array originally so that should give a vectorised answer of 3 values also (though I haven't checked carefully to see if there are any further e.g. .^ or .* missing to make it work on vector inputs).
If you really want to use a for loop then the switch doesn't make sense there either though.
Just use
I(i)
instead (though clearly you need some better variable names for readability!) and put the result into
K_R(i)
which you should pre-size before the for loop as e.g.
K_R = zeros( size( I ) );

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

採用された回答

Andrei Bobrov
Andrei Bobrov 2019 年 10 月 17 日
編集済み: Andrei Bobrov 2019 年 10 月 17 日
% Parameters
a_R = 0.0325;
a_T = 0.0325;
N_T = 164;
N_R = 10;
mu_0 = 4*pi*(10^-7);
f_Array = [10000,20000,40000];
w = 2*pi*f_Array; % Angular frequency
I = [2,1,0.5]'; % Current
K_R = mu_0^2*w.^2*pi*N_T*N_R*a_T^2*a_R^2.*I/(4*x_R_center);
If you use old MATLAB (R < 2016a), so last expresion:
K_R = mu_0^2*pi*N_T*N_R*a_T^2*a_R^2/(4*x_R_center)*bsxfun(@times,w.^2,I);

その他の回答 (0 件)

カテゴリ

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