簡體   English   中英

for循環的條件語句

[英]conditional statement with for loop

不知道我在這里做錯了什么;

我正在嘗試使用以下函數的條件語句進行for循環。 我想做到,所以h不是向量。 我這樣做是1到5,增量為0.1。

Y = f(h) = h^2    if h <= 2 or h >= 3
Y = f(h) = 45     otherwise

我的代碼是

for h = 0:0.1:5
if h <= 2;
   Y = h^2;
elseif h >= 3;
Y = h^2;
else;
   h = 45;
end
end

這可以更輕松地完成,但是我想使用for循環可以使用:

h=0:0.1:5;
y=zeros(1,length(h));

for i=1:length(h)
    if or(h(i) <= 2, h(i) >= 3)
       y(i) = h(i)^2;
    else
       y(i) = 45;
    end
end

為什么要避免將h制成數組? MATLAB專長於數組的運算。 實際上,MATLAB中的矢量化運算通常比for循環快,我發現違反直覺的人已經開始使用C ++進行編碼。

您的代碼的向量化版本的示例可能是:

h = 0:0.1:5;
inds = find(h > 2 & h < 3);  % grab indices where Y = 45
Y = h.^2;  % set all of Y = h^2
Y(inds) = 45;  % set only those entries for h between 2 and 3 to 45

.^2運算符中的句點將該運算符廣播到h數組中的每個元素。 這意味着您最終將h每個數字平方。 通常,像這樣的矢量化操作在MATLAB中效率更高,因此最好養成對代碼進行矢量化的習慣。

最后,您可以通過不存儲索引來減少上面的代碼:

h = 0:0.1:5;
Y = h.^2;  % set all of Y = h^2
Y(find(h > 2 & h < 3)) = 45;  % set only those entries for h between 2 and 3 to 45

這個博客系列似乎是對矢量化MATLAB代碼的一個很好的入門。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM