gpt4 book ai didi

MATLAB bsxfun 或向量化

转载 作者:太空宇宙 更新时间:2023-11-03 20:04:58 27 4
gpt4 key购买 nike

我主要使用 bsxfun 对我的代码进行矢量化,但我遇到了一个我无法完全破解的场景。这是一个小问题示例。我想删除此代码中的 for 循环,但我很难处理 tempEA 行。

Index = [2; 3; 4;];

dTime = [25; 26; 27; 28; 25; 26; 27; 28; 27; 28];
dIndex = [3; 3; 3; 2; 1; 3; 2; 4; 4; 2];
aTime = [30; 38; 34; 39; 30; 38; 34; 39; 34; 39];
aIndex = [4; 2; 5; 4; 5; 4; 4; 2; 2; 4];

EA = zeros(numel(Index));
for i = 1:numel(Index)
for j = 1:numel(Index)
tempEA = aTime(Index(i) == dIndex(:,1) & Index(j) == aIndex(:,1));
if i == j
elseif tempEA > 0
EA(i,j) = min(tempEA);
else
EA(i,j) = 50;
end
end
end

答案应该是这样的:

EA =

0 50 34
38 0 30
34 50 0

提前感谢您的帮助。

最佳答案

这使用 bsxfun ;没有循环。它假定您没有 NaN在你的aTime中值(value)观。

N = numel(Index);
ii = bsxfun(@eq, dIndex.', Index); %'// selected values according to each i
jj = bsxfun(@eq, aIndex.', Index); %'// selected values according to each j
[ igrid jgrid ] = ndgrid(1:N); %// generate all combinations of i and j
match = double(ii(igrid(:),:) & jj(jgrid(:),:)); %// each row contains the matches for an (i,j) combination
match(~match) = NaN; %// these entries will not be considered when minimizing
result = min(bsxfun(@times, aTime, match.')); %'// minimize according to each row of "match"
result = reshape(result,[N N]);
result(isnan(result)) = 50; %// set NaN to 50
result(result<=0) = 50; %// set nonpositive values to 50
result(1:N+1:end) = 0; %// set diagonal to 0

result(result<=0) = 50;仅在您的 aTime 时才需要可以包含非正值。它可以?或者是你的 elseif tempEA > 0只是一种检查 tempEA 的方法不为空?

关于MATLAB bsxfun 或向量化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19744447/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com