function performance, same functions has very different speed

1 回表示 (過去 30 日間)
Alexander Malafeev
Alexander Malafeev 2013 年 5 月 2 日
Dear forum, I have two functions
function [Md] = MDx( M, dx )
w = size(M,2);
for i=2:w-1
Md(:,i) = ( M(:,i+1) - M(:, i-1) )/(2*dx);
end
Md(:,1) = ( M(:,2) - M(:, 1) )/dx;
Md(:,w) = ( M(:,w) - M(:, w-1) )/dx;
return
and
function [Md] = MDy( M, dy )
h = size(M,1);
for i=2:h-1
Md(i,:) = ( M(i+1,:) - M(i-1, :) )/(2*dy);
end
Md(1,:) = ( M(2,:) - M(1, :) )/dy;
Md(h,:) = ( M(h,:) - M(h-1,:) )/dy;
return
this functions are computing gradient in X and Y directions, they are quite same but on square matrix MDx is 40 times faster than MDy, what is the reason for that?

回答 (1 件)

John Doe
John Doe 2013 年 5 月 2 日
編集済み: John Doe 2013 年 5 月 2 日
I believe this is due to the way matrices are stored in Matlab.
A matrix is stored column-wise, as below:
A = [1 2 3;4 5 6;7 8 9];
A(1,1) = A(1) = 1;
A(2,1) = A(2) = 4;
...
A(1,3) = A(7) = 3;
A(:,1) = A(1:3);
A(1,:) = A([1 4 7]);
This makes it faster to do calculations on entire columns, rather than rows, thus MDx is fastest.

カテゴリ

Help Center および File ExchangeSchedule Model Components についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by