avoid loop in matrix multiplicatoion

1 回表示 (過去 30 日間)
AMAL targhi
AMAL targhi 2016 年 7 月 17 日
コメント済み: Walter Roberson 2016 年 7 月 17 日
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.
Walter Roberson
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 ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by