avoid loop in matrix multiplicatoion
Mostrar comentarios más antiguos
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
Respuestas (1)
Walter Roberson
el 17 de Jul. de 2016
0 votos
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 comentarios
AMAL targhi
el 17 de Jul. de 2016
Editada: AMAL targhi
el 17 de Jul. de 2016
Walter Roberson
el 17 de Jul. de 2016
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
el 17 de Jul. de 2016
See also https://www.mathworks.com/matlabcentral/fileexchange/33341-quaternion-m which has an mtimes() operation which might be what you need.
Categorías
Más información sobre Scope Variables and Generate Names en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!