[英]sum condition applied on possible permutations of a vector without a loop MATLAB
[英]Matlab, if condition without loop
在循環內有A(n,1),B(n,1)和以下條件
for i=1:m
if ( A(i, 1) > error )
B(i,1) = 0;
else
B(i,1) = exp (-A(i,1) / 100)
end
end
如何在不使用任何循環的情況下重寫此條件? 有可能是這樣的
if ( A(:, 1) > error )
B(:,1) = 0;
else
B(:,1) = exp (-A(:,1) / 100)
end
使用邏輯索引 :
idxs = (A > error);
B( idxs) = 0;
B(~idxs) = exp(-A(~idxs) / 100);
你接近你的建議。 關鍵是要形成一個“邏輯指數”。
i = A(:,1) > error;
B(i,:) = 0;
B(~i,:) = exp (-A(:,1) / 100);
由於你的矩陣A和B是向量(一維矩陣),在這種情況下不需要(:,1)
和(i,:)
,但是因為它們在你的初始公式中,我把它們留在了。如果你使用多維矩陣代替(m * n)你可以通過做i = A > error;
形成一個(m * n)邏輯索引而不是(m * 1) i = A > error;
而不是i = A(:,1) > error;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.