If you give an input matrix of c = ((rand10,20)>0.5)*2)-1
the code below will give an answer for each column seperately. Why does it do this? shouldn't this code just sum all answers and give a single number?
is it possible to create the same output with nested for loops?
function f = autocorrelation(a)% autocorrelation(a); a: column vector, {-1,+1}
n = length(a(:,1));
for (k=1:1:n-1) % (Start:step:end)
E(k,:) = (sum(a(1:n-k,:) .* (a(1+k:n,:)),1)).^2;
end
f = n^2 ./ (2 * sum(E));
end

1 件のコメント

Guillaume
Guillaume 2016 年 10 月 11 日
I've formatted your post a bit better. Please remove the # that you added and prevent us from copying your code.
In the future to format text as code click on the {} Code button (or add two spaces before each line)

サインインしてコメントする。

 採用された回答

Guillaume
Guillaume 2016 年 10 月 11 日

2 投票

By default, sum sums all the elements of each column together. You can change whether it sums by column, row, or other dimension, by specifying the dim argument as you've done inside your loop:
E(k, :) = sum(something, 1) .^ 2; %personally, if find the unnecessary brackets makes your expression harder to read.
1 is the default for matrix (for vector it's whichever dimension is not singleton), as clearly explained in the sum documentation.
In your f expression, where you don't specify a dimension, the default 1 is used and E is again summed by column.
If you want to sum all the elements of a matrix together, you first need to reshape that matrix into a single column of row:
f = 0.5 * n^2 / sum(E(:)); %E(:) reshape E into one column
%or
f = 0.5 * n^2 / sum(reshape(E, 1, [])); %explicit reshape
Note:
n = size(a, 1);
is much clearer and shorter than
n = length(a(:, 1));
and also won't give an error if a is empty.

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索

質問済み:

2016 年 10 月 11 日

回答済み:

2016 年 10 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by