I have a 4D array A
size(l,k,s,r) and a cell array B
size(i,j) where in each cell a different 4D array of coefficients size(l,k,s,r) is stored.
I want to make changes in the given array C
of size(i,j) = C(i,j) + sum(sum(sum(sum(A.*B{i,j}))))
without for
loop.
in other words I need to extract one by one all arrays out of cell array B
and multiply with A
.
with the for loop i do it this way:
for i=1:length_of_first_dimension
for j=1:length_of_second_dimension
B_4D=B{i,j}; % extraction of 4D array
dummy(i,j)=sum(sum(sum(sum(B_4D.*A))));
end
end
C=C+dummy;
can anyone help me with that?
first, reshape
B
into a (length_of_first_dimension*length_of_second_dimension)
-by- l*k*s*r
2D matrix
rB = cellfun( @(x) x(:).', B, 'uni', 0 ); %'
rB = vertcat(rB{:});
Now, reshape
A
into a l*k*s*r
-by-1 column vector
rA = A(:);
And simply multiply them
rDummy = rB * rA; %// does the elem-wise product and summation quite quickly.
Reshape the result
dummy = reshape(rDummy, size(B) );
C = C + dummy;
As pointed by Divakar a more efficient way to reshape
B
would be
rB = reshape( cat( 5, B{:} ), numel(A), [] ).';
And a small benchmark can be found here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.