필터 지우기
필터 지우기

Correlation between 2 vectors give a matrix full of Nan

조회 수: 2 (최근 30일)
marcello
marcello 2023년 10월 30일
댓글: Voss 2023년 10월 31일
Hi, im trying to calculate the correlation between the vector cost and cost2:
A=5;
f=1;
ph1=0;
cost=A*cos(pi*f*t+ph1);
cost2 = A*cos(2*(pi*f*t+ph1))+1;
I need to draw the graphic of the correlation but the result is a matrix full of Nan and the plot is blank graph.
I've already tried to use c = corr(cost,cost2,'rows','complete') but the result is still a matrix full of Nan values.

채택된 답변

Voss
Voss 2023년 10월 30일
From the documentation for corr:
rho = corr(X) returns a matrix of the pairwise linear correlation coefficient between each pair of columns in the input matrix X.
If t is a row vector (unknown since t was not given), then your vectors are row vectors, so each column is a single element. You don't want to be calculating correlations between one element and another element; you want the correlation between one entire vector and the other entire vector, so make them into column vectors so that corr can operate on them properly.
t = 0:0.01:1;
A=5;
f=1;
ph1=0;
cost=A*cos(pi*f*t+ph1);
cost2 = A*cos(2*(pi*f*t+ph1))+1;
c = corr(cost(:),cost2(:),'rows','complete')
c = 1.4630e-16
plot(cost)
hold on
plot(cost2)

추가 답변 (1개)

Walter Roberson
Walter Roberson 2023년 10월 30일
편집: Walter Roberson 2023년 10월 30일
t = linspace(0,1) .'; %COLUMN
A=5;
f=1;
ph1=0;
cost=A*cos(pi*f*t+ph1);
cost2 = A*cos(2*(pi*f*t+ph1))+1;
c = corr(cost,cost2,'rows','complete')
c = 1.1679e-16
Perhaps you are expecting a correlation for each t value.
When you pass in an N x M first parameter and an P x Q second parameter and request 'rows' then the number of rows must be equal -- so N x M and N x Q . The size of the output would then be M x Q -- number of columns of the first times number of columns of the second. Unless, that is, the data you pass in only has one row, in which case the outputs will be all NaN.
I suspect you passed in two row vectors, in which case you would get out size(cost,2) by size(cost2,2) of all NaN.

카테고리

Help CenterFile Exchange에서 Correlation and Convolution에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by