How can I avoid looping here?

1 回表示 (過去 30 日間)
Behrooz Daneshian
Behrooz Daneshian 2023 年 1 月 20 日
編集済み: Alberto Cuadra Lara 2023 年 1 月 20 日
Hi all,
I want to avoid using for loop in part of my code to make it more efficient. Can anyone give me idea regarding this?
STD_w=0.05;
STD_gama=5;
mean_w=linspace(15,40,10);
sigma_w=ones(1,length(mean_w))*STD_w;
mean_gama=linspace(115,85,10);
sigma_gama=ones(1,length(mean_w))*STD_gama;
mean_k=zeros(1,length(mean_w));
mean_L=zeros(1,length(mean_w));
for j=1:length(mean_w)
mean_k(j)=(0.0833/2)*(0.01*10^(0.022*mean_gama(j))+0.085*10^(0.008*mean_gama(j))*mean_w(j)+(0.9*log10(mean_w(j))-0.2)*10^(0.01*mean_gama(j)));
mean_L(j)=144*0.01*mean_w(j)*mean_gama(j);
end

採用された回答

Torsten
Torsten 2023 年 1 月 20 日
STD_w=0.05;
STD_gama=5;
mean_w=linspace(15,40,10);
sigma_w=ones(1,length(mean_w))*STD_w;
mean_gama=linspace(115,85,10);
sigma_gama=ones(1,length(mean_w))*STD_gama;
mean_k=(0.0833/2)*(0.01*10.^(0.022*mean_gama)+0.085*10.^(0.008*mean_gama).*mean_w+(0.9*log10(mean_w)-0.2).*10.^(0.01*mean_gama))
mean_k = 1×10
1.0879 1.1155 1.1314 1.1384 1.1386 1.1332 1.1234 1.1100 1.0936 1.0748
mean_L=144*0.01*mean_w.*mean_gama
mean_L = 1×10
1.0e+03 * 2.4840 2.8587 3.2067 3.5280 3.8227 4.0907 4.3320 4.5467 4.7347 4.8960

その他の回答 (1 件)

Alberto Cuadra Lara
Alberto Cuadra Lara 2023 年 1 月 20 日
編集済み: Alberto Cuadra Lara 2023 年 1 月 20 日
Hello Behrooz,
By using elementwise operators {.* .^ ./}.
Best,
Alberto
% Definitions
STD_w=0.05;
STD_gama=5;
mean_w=linspace(15,40,10);
sigma_w=ones(1,length(mean_w))*STD_w;
mean_gama=linspace(115,85,10);
sigma_gama=ones(1,length(mean_w))*STD_gama;
mean_k=zeros(1,length(mean_w));
mean_L=zeros(1,length(mean_w));
% With loop
for j=1:length(mean_w)
mean_k(j)=(0.0833/2)*(0.01*10^(0.022*mean_gama(j))+0.085*10^(0.008*mean_gama(j))*mean_w(j)+(0.9*log10(mean_w(j))-0.2)*10^(0.01*mean_gama(j)));
mean_L(j)=144*0.01*mean_w(j)*mean_gama(j);
end
% Without loop
mean_k_2 = (0.0833/2)*(0.01*10.^(0.022*mean_gama) + 0.085*10.^(0.008*mean_gama) .* mean_w + (0.9*log10(mean_w)-0.2) .* 10.^(0.01*mean_gama));
mean_L_2 = 144 * 0.01 * mean_w .* mean_gama;
% Checks
FLAG_CHECKS = isequal(mean_k, mean_k_2) && isequal(mean_L, mean_L_2)
FLAG_CHECKS = logical
1

カテゴリ

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