【问题标题】:MATLAB: Rewriting same operations on 2 Structures without a loop?MATLAB:在没有循环的情况下重写 2 个结构的相同操作?
【发布时间】:2013-03-08 12:24:18
【问题描述】:

给定矩阵M(x 乘以5)和结构thr,其中包含数字,我如何在没有循环的情况下执行以下过程?

structfun 不能用于 2 个结构。无法使用arrayfun 分配给我的结构indexcellfun 也不是正确的。有人帮忙吗?

提前谢谢你!

index.b = M(:,1) >= thr.b;
index.c = M(:,2) >= thr.c;
index.h = M(:,3) >= thr.h;
index.r = M(:,4) >= thr.r;
index.s = M(:,5) >= thr.s;

【问题讨论】:

  • 也许结构不是最好的数据结构?为什么不I = M > T T(:, 1) = thr.b 等等...?
  • 感谢@Dan,这个想法还不错。但它的计算方式与上述不同。到M 的每一列的链接都丢失了。应该是M(:,1) > T(1)
  • 不,我建议size(M) == size(T) 所以T = repmat([thr.b, thr.c, thr.h,...], size(M, 1), 1) 例如

标签: matlab loops struct


【解决方案1】:

如果您确实需要维护您的数据结构,这里是一个解决方案。

首先,让我们创建虚拟输入:

M = rand(5);
index = struct('b',[],'c',[],'h',[],'r',[],'s',[]);
thr = struct('b',.5,'c',.5,'h',.5,'r',.5,'s',.5);

这是真正的技巧:

A = bsxfun(@ge, M, [thr.b, thr.c, thr.h, thr.r, thr.s]);
A = num2cell(A,1);
[index.b, index.c, index.h, index.r, index.s] = deal(A{:});

同样,您可以使用适当的数据结构以更有效的方式执行此操作。 希望这会有所帮助。

【讨论】:

  • 谢谢@upperBound,合适的数据结构应该是什么?你的意思是丹在上一个答案中展示的方式吗?
猜你喜欢
  • 2016-07-13
  • 2013-02-16
  • 2013-10-24
  • 1970-01-01
  • 2014-08-25
  • 1970-01-01
  • 2018-01-27
  • 2022-08-19
  • 2015-02-12
相关资源
最近更新 更多