首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MATLAB bsxfun或矢量化

MATLAB bsxfun或矢量化
EN

Stack Overflow用户
提问于 2013-11-02 16:59:55
回答 1查看 557关注 0票数 4

我一直致力于将代码向量化,主要是使用bsxfun,但我遇到了一个无法完全破解的场景。这是一个小问题的例子。我想删除这段代码中的for循环,但是我很难使用tempEA行。

代码语言:javascript
运行
复制
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

答案应该是这样的:

代码语言:javascript
运行
复制
EA =

     0    50    34
    38     0    30
    34    50     0

谢谢你提前帮忙。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-02 17:30:39

这使用bsxfun;没有循环。它假设在您的NaN值中没有aTime值。

代码语言:javascript
运行
复制
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是否为空的一种方式?

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19744447

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档