Rearranging rows using unique values in column

If I have a matrix as follows: The first column is unique ID while the second column represents price:
x = [106 2;
106 4;
109 3;
109 7;
109 11;
106 3;
106 6;
109 16]
I want to arrange the matrix using the unique values in the first column to get the following:
x = [106 2;
106 4;
106 3;
106 6;
109 3;
109 7;
109 11;
109 16]
After arranging the matrix I want to calculate the change in prices for each unique ID to get the following
newdatawithchange = [106 2 --;
106 4 2;
106 3 -1;
106 6 3;
109 3 --;
109 7 4;
109 11 4;
109 16 5]
Then, how can I calculate the correlation between values in the second and third column but unique for each ID (There will be a coefficient for ID 106 and another coefficient for ID 109 with skipping the first row for each ID as there is no value for the change)

 채택된 답변

Image Analyst
Image Analyst 2017년 5월 5일

0 개 추천

To sort it is easy:
x = [106 2;
106 4;
109 3;
109 7;
109 11;
106 3;
106 6;
109 16]
sortedX = sortrows(x, 1)

댓글 수: 7

Mido
Mido 2017년 5월 5일
Thanks for you help. This works and I appreciate your help in the rest.
I was hoping you'd be able to get it yourself. Here's a full solution:
x = [106 2;
106 4;
109 3;
109 7;
109 11;
106 3;
106 6;
109 16]
sortedX = sortrows(x, 1)
% Find difference between a row and the one above it.
column3 = [0; sortedX(2:end, 2) - sortedX(1:end-1, 2)]
% Find out where the number switches and set those to 0
startRows = [0, find(d)] + 1
column3(startRows) = 0;
% Stitch to right side
output = [sortedX, column3]
There may be other ways of doing it.
Mido
Mido 2017년 5월 5일
Thanks but what is d as when running the code, I receive the following message (Undefined function or variable 'd').
Mido
Mido 2017년 5월 5일
d = diff(sortedX(:,1)) Thanks
Mido
Mido 2017년 5월 5일
What about the part of the correlation, Is a way to do it?
Is this homework? I think you would learn more if you tried something yourself than just asking me to do it all for you. For example, did you look up corr in the help? Did you see this:
RHO = corr(X,Y) returns a p1-by-p2 matrix containing the pairwise correlation coefficient between each pair of columns in the n-by-p1 and n-by-p2 matrices X and Y.
The difference between corr(X,Y) and the MATLAB® function corrcoef(X,Y) is that corrcoef(X,Y) returns a matrix of correlation coefficients for the two column vectors X and Y. If X and Y are not column vectors, corrcoef(X,Y) converts them to column vectors.
I don't think this is beyond your capabilities, is it? Just pass in the second and third columns, except for the rows I identified as startRows. X is col2 and Y is col3. Give it a try.
Mido
Mido 2017년 5월 5일
Thank you.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2017년 5월 5일

댓글:

2017년 5월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by