Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
matlab:cellfun逻辑_Matlab_Bsxfun - Fatal编程技术网

matlab:cellfun逻辑

matlab:cellfun逻辑,matlab,bsxfun,Matlab,Bsxfun,我有一个(对我来说相当复杂的)cellfun操作,我需要一个明智的头脑来观察它,判断它是否真的在做我想做的事情: b = cellfun(@(x) nansum(bsxfun(@times, mag(:),cross(u{1},x))),r,'UniformOutput',false); size(mag) ans = 81 3 size(u{1}) ans = 81 3 size(r) ans = 1 81 u和r是单元阵

我有一个(对我来说相当复杂的)cellfun操作,我需要一个明智的头脑来观察它,判断它是否真的在做我想做的事情:

b = cellfun(@(x) nansum(bsxfun(@times, mag(:),cross(u{1},x))),r,'UniformOutput',false);

 size(mag)

ans =

    81     3

 size(u{1})

ans =

    81     3

size(r)

ans =

     1    81
u和r是单元阵列。我需要的算法是:

->取u{1}的每个元素,并与r{1}的每个元素交叉乘积。 ->将得到的81 x 3单元与mag(尺寸81 x 3)相乘。 ->取u{1}的每个元素,并与r{2}的每个元素交叉乘积。 ->将得到的81 x 3单元与mag(尺寸81 x 3)相乘

等等

我得到以下错误:

??? Error using ==> bsxfun
Non-singleton dimensions of the two input arrays must match each other.

Error in ==> cellcross>@(x)nansum(bsxfun(@times,mag(:),cross(u{1},x))) at 2
    b = cellfun(@(x) nansum(bsxfun(@times, mag(:),cross(u{1},x))),r,'UniformOutput',false);

Error in ==> cellcross at 2
    b = cellfun(@(x) nansum(bsxfun(@times, mag(:),cross(u{1},x))),r,'UniformOutput',false);
我的逻辑在哪里?将mag更改为单元阵列(如u),然后使用cellfun进行多重应用是否更容易

还将指出,移除mag:

b = cellfun(@(x) nansum(cross(u{1},x)),r,'UniformOutput',false);
正如预期的那样工作,因此将结果乘以u是一个问题

编辑gunthers评论:

假设我有两个物体u和r,它们都是细胞

u =

1 1 0              1st element
2 2 0              2nd element
3 3 0              3rd element

r =

3 3 0
2 2 0
1 1 0
我想做的就是:

cross(u{1},r{1})
=交叉([11,0],[3,3,0])+交叉([22,0],[2,2,0])+交叉([3,0],[1,1,0]))

然后重复:

 sum(cross(u{1},r{2}))
 sum(cross(u{1},r{3}))
 . 
 .
 . 
 .

对我来说,检查整个过程并确保结果是正确的有点困难,但从第一个近似值来看,唯一的问题似乎是你的叉积失败了,因为你用
mag(:)
使它变为243x1,就像这样

>> size(mag(:))
ans =
243     1
>> size(mag)
ans =
81     3
这导致您的
@times
产品失败,正如您的错误所示。所以改变后的电话是

cellfun(@(x) nansum(bsxfun(@times, mag,cross(u{1},x))),r,'UniformOutput',false)

通读你的话并不容易,你能添加一个循环示例吗?它符合你的要求吗?如果你有一个循环,那么在大多数情况下很容易转换成一个
cell/array/…fun
调用(假设没有递归、相互依赖等)@GUnther请看我编辑的帖子(为GUnther编辑)@brucezepplin你有什么特别的原因试图使用
cellfun
而不是循环吗?在这种情况下,for循环可能会产生更干净、更容易理解/调试的代码。此外,for循环的执行速度当然可能与
cellfun
一样快(如果不是更快的话)。(显然,您希望使用tic/toc或MATLAB Profiler来查看这是否适用于您的特定用例)