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
댓글 수: 0
답변 (1개)
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
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!