Reputation: 9752
I have the following two vector fields:
>> 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]
and I need to take the cross product of pairwise elements i.e.
b = (cross(orient{1,1},distance{1,1}) + cross(orient{1,2},distance{1,2})..... and so on
and then reshape to match the dimensions of distance and orient.
Can I do this without using a for loop?
and what about if I have
orient{1,1} =
[1x3 double]
distance =
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
[1x3 double] [1x3 double] [1x3 double]
how do I do
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}) +...)
where each 'sum' is just an iteration of a single orient element, crossed with all the elements of distance, and then those cross products are summed. I would then have:
mastersum = sum1 sum2 sum3
sum4 sum5 sum6
sum6 sum8 sum9
where
sum1 =
[1x3 double]
Am I just putting this in a confusing way?
Upvotes: 3
Views: 1748
Reputation: 32930
You'll need to use cellfun
to traverse the cell arrays without a for
-loop.
For two vector fields (two cell arrays), you should do:
crosses = cellfun(@(u, v)cross(u, v)', orient, distance, 'UniformOutput', 0);
b = sum(cell2mat({crosses{:}})', 1) %# Summing all vectors in all cells
A similar procedure for single cell from orient
, say orient{1, 2}
, would be:
u = orient{1, 2};
crosses = cellfun(@(v)cross(u, v)', distance, 'UniformOutput', 0);
b = sum(cell2mat({crosses{:}})', 1) %# This command remains the same
To get the result for all vectors from orient
without a for
loop, do instead:
b_func = @(u)sum(cell2mat(cellfun(@(v)cross(u,v)', {distance{:}}, 'Un', 0))', 1);
U = cellfun(b_func, orient, 'UniformOutput', 0)
Now U
is also a cell array (of the same dimensions as orient
): U{1, 1}
has the sum of crosses for orient{1, 1}
, U{1, 2}
for orient{1, 2}
, and so on...
Upvotes: 4