avoid loop in matrix multiplicatoion
显示 更早的评论
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
2016-7-17
0 个投票
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 个评论
AMAL targhi
2016-7-17
编辑:AMAL targhi
2016-7-17
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.
Walter Roberson
2016-7-17
See also https://www.mathworks.com/matlabcentral/fileexchange/33341-quaternion-m which has an mtimes() operation which might be what you need.
类别
在 帮助中心 和 File Exchange 中查找有关 Scope Variables and Generate Names 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!