Create new variable that recognizes changes in the code

조회 수: 2 (최근 30일)
Maria
Maria 2014년 7월 22일
댓글: Geoff Hayes 2014년 7월 24일
I have a double matrix B that has in C1 the year 1998 and in C2 a code (unrepeated). Each C2 is given a value in C3.
% C1 C2 C3
B=[ 1998 22 37
1998 34 7
1998 76 12
1998 98 29
1998 107 14
]
This is how I got to B:
N1=[N{:,1} N{:,2} N{:,3}];
N1=unique(N1(:,1:3),'rows');
N3= unique(N1(:,1:2),'rows');
for m=1:size(N3,1)
N3(m,3)=sum(N1(:,1) == N3(m,1) & N1(:,2)==N3(m,2));
end
B=N3((N3(:,1) == 1998),:);
I have a cell-array A with the years horizontally disposed in R1, un-repeated values in Y, and corresponding codes in the columns that follow. The codes are the same as in C2 from variable B, but disposed differently.
A={Y 1996 1997 1998 1999 %R1
1 107 107 22 22
13 98 98 76 1267
}
Is there a way I could get a new variable that recognizes the change in the codes in variable A, and presents the corresponding values from C3 in B? For instance:
AB={Y Initial C2 Change C2
1 107 14 22 37
13 98 29 76 12 }

채택된 답변

Geoff Hayes
Geoff Hayes 2014년 7월 22일
Given the A and B from above (less the incomplete portions), you could iterate over each row of A and compare the second and fourth values with that from distinct second column of B, looking for a match. If a match is found, then replace the third and fifth values form AB with those from B (if a match for both can be found)
% initialize AB to that of A
AB = A;
% iterate over each row of A
for k=1:size(A,1)
% search the second column of B for the second element of A
idx = find(B(:,2)==A{k,2});
if ~isempty(idx)
% replace
AB{k,3} = B(idx,3);
else
% not found, so set to empty (?)
AB{k,3} = [];
end
% search the second column of B for the fourth element of A
idx = find(B(:,2)==A{k,4});
if ~isempty(idx)
% replace
AB{k,5} = B(idx,3);
else
% not found, so set to empty (?)
AB{k,5} = [];
end
end
Try the above and see what happens!
  댓글 수: 7
Maria
Maria 2014년 7월 24일
Finally it's working! Thanks for the help!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by