1 view (last 30 days)

I use the built-in fft() function on a 2D single matrix of size 71*110000. Initially, I looped over the first dimension. However, passing the whole matrix to fft() results in ~30% speedup, which is why I'd like to continue with that. What's puzzling me is that the results are similar but not the same. My understanding from the documentation is that Matlab would do the exact same computation, treating each row as a vector in the matrix case. I'd be thankful for any idea why the results differ.

Example:

%% generate random data

data = single(rand(71, 110000));

n = 111872;

%% loop version

for ichan = 1:size(data, 1)

dataX(ichan, :) = fft(data(ichan, :), n);

end

%% matrix version

alldataX = fft(data, n, 2);

%% test

isequal(dataX, alldataX)

isequaln(dataX, alldataX)

max(abs(dataX - alldataX)) %small difference, but not the same

Matt J
on 11 Oct 2019

Edited: Matt J
on 11 Oct 2019

The same dicrepancy exists with most Matlab functions that do operations along rows or columns. Here is the same test replacing fft with sum,

%% generate random data

data = single(rand(71, 110000));

dataX=data(:,1);

%% loop version

for ichan = 1:size(data, 1)

dataX(ichan) = sum(data(ichan, :), 2);

end

%% matrix version

alldataX = sum(data, 2);

%% test

isequal(dataX, alldataX)

isequaln(dataX, alldataX)

max(abs(dataX(:) - alldataX(:)))/max(alldataX(:))*100 %4.2499e-05

The reason for it is that Matlab's internal multi-threading splits the data up differently depending on the size of the array given as input to the function. This leads to summations being done in different orders and hence floating point discrepancies in the results.

Opportunities for recent engineering grads.

Apply Today
## 3 Comments

## Direct link to this comment

https://ww2.mathworks.cn/matlabcentral/answers/484767-why-do-results-of-fft-on-a-matrix-differ-from-fft-on-one-row-as-a-vector#comment_755143

⋮## Direct link to this comment

https://ww2.mathworks.cn/matlabcentral/answers/484767-why-do-results-of-fft-on-a-matrix-differ-from-fft-on-one-row-as-a-vector#comment_755143

## Direct link to this comment

https://ww2.mathworks.cn/matlabcentral/answers/484767-why-do-results-of-fft-on-a-matrix-differ-from-fft-on-one-row-as-a-vector#comment_755144

⋮## Direct link to this comment

https://ww2.mathworks.cn/matlabcentral/answers/484767-why-do-results-of-fft-on-a-matrix-differ-from-fft-on-one-row-as-a-vector#comment_755144

## Direct link to this comment

https://ww2.mathworks.cn/matlabcentral/answers/484767-why-do-results-of-fft-on-a-matrix-differ-from-fft-on-one-row-as-a-vector#comment_755171

⋮## Direct link to this comment

https://ww2.mathworks.cn/matlabcentral/answers/484767-why-do-results-of-fft-on-a-matrix-differ-from-fft-on-one-row-as-a-vector#comment_755171

Sign in to comment.