我有以下两个矢量字段:
>> orient
orient =
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
>> distance
distance =
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
我需要采用成对元素的叉积,即
b = (cross(orient{1,1},distance{1,1}) + cross(orient{1,2},distance{1,2})..... and so on
然后重新塑造以匹配距离和方向的尺寸。
我可以不使用for循环吗?
如果我有
怎么办?orient{1,1} =
[1x3 double]
distance =
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
我该怎么做
sum1 =(cross(orient {1,1},distance {1,1})+ cross(orient {1,1},distance {1,2})+ ...) sum2 =(cross(orient {1,2},distance {1,1})+ cross(orient {1,2},distance {1,2})+ ...)
其中每个'sum'只是单个方向元素的迭代,与所有距离元素交叉,然后将这些交叉乘积相加。然后我会:
mastersum = sum1 sum2 sum3
sum4 sum5 sum6
sum6 sum8 sum9
其中
sum1 =
[1x3 double]
我只是把它放在一个令人困惑的方式吗?
答案 0 :(得分:4)
您需要使用cellfun
来遍历没有for
- 循环的单元格数组。
对于两个矢量场(两个单元阵列),您应该这样做:
crosses = cellfun(@(u, v)cross(u, v)', orient, distance, 'UniformOutput', 0);
b = sum(cell2mat({crosses{:}})', 1) %# Summing all vectors in all cells
来自orient
的单个单元格的类似程序,例如orient{1, 2}
,将是:
u = orient{1, 2};
crosses = cellfun(@(v)cross(u, v)', distance, 'UniformOutput', 0);
b = sum(cell2mat({crosses{:}})', 1) %# This command remains the same
要获取orient
没有for
循环的所有向量的结果,请改为:
b_func = @(u)sum(cell2mat(cellfun(@(v)cross(u,v)', {distance{:}}, 'Un', 0))', 1);
U = cellfun(b_func, orient, 'UniformOutput', 0)
现在U
也是一个单元格数组(与orient
具有相同的维度):U{1, 1}
包含orient{1, 1}
,U{1, 2}
的十字总和orient{1, 2}
,等等......