avoid loop in matrix multiplicatoion

1 次查看(过去 30 天)
This is a function to multiply 2 matrix ( of quaternions) i need to avoid loops what should i do
function a = matrice_multplication(A, B)
[r1 , c1] = size(A);
[r2 , c2] = size(B);
% % prevent unappropriate matrix size
if c1 ~= r2
disp ('*** le nombre des colonne de la premiere matrice doit etre egale ou nombre des ligne de la deuxieme matrice ***')
end
for i = 1 : r1
% Vary each column of matrix B
for j = 1 : c2
% Reset every new element of the final result
% c=cell (r1 , c2)
s = [0,0,0,0] ;
% Vary each column of matrix A and row of matrix B
for k = 1 : c1
% Display every element to take into account
% disp( A{i,k})
% disp ( B{k,j})
% f= )
s =plus(s,quatmultiply(A{i,k},B{k,j}) );
%
end
% % Assign the total of the appropriate element
% % to the final matrix
c{i,j} = s;
% disp ( c{1,1})
% disp ( c{1,2})
% disp ( c{2,1})
% disp ( c{2,2})
a{i,j} = c{i,j};
% disp (a{i,j})
end
end
end

回答(1 个)

Walter Roberson
Walter Roberson 2016-7-17
When you use cell arrays to represent your data, it is not possible to avoid the loops: it is only possible to hide the loops, such as by using cellfun(), or by converting the cells to matrices and manipulating those (cell2mat uses loops internally.)
  3 个评论
Walter Roberson
Walter Roberson 2016-7-17
You can replace your "k" loop with something like
c{i,j} = sum( cell2mat( cellfun(@quatmultiply, A(i,:), B(:, j).', 'Uniform', 0).' ) );
To do the whole thing without any explicit loop at all would probably require something like ndgrid to create the matrix of indices and then arrayfun() the above operation.
Removing explicit loops is often less efficient, when you replace the loops with function calls and contrived temporary arrays.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by