필터 지우기
필터 지우기

How to construct an array from two arrays of different sizes using conditional replacement of elements?

조회 수: 1 (최근 30일)
Hi, I have two arrays A and B as below
A=load('A.txt');
B=load('B.txt');
where
A=
1
2
3
4
5
6
7
8
9
10
and
B=
1 4
3 10
6 15
8 17
9 59
Goal: I want to construct an array C with the same length as A. The elements of C equals the elements of the second column of B if the elements of the first column of A and the elements of the first column of B are equal. Otherwise, the elements of C is not available (NaN)
Thus, C should look like below:
C=
1 4
2 NaN
3 10
4 NaN
5 NaN
6 15
7 NaN
8 17
9 59
10 NaN
I tried the following command lines:
C=zeros(size(A));
for i=1:numel(A);
for j=1:numel(B);
if A(i)=B(j);
C(i)=B(j,2);
else
C(i) = NaN;
end;end;
but had no success yet. I wonder if someone could help me to correct the mistakes I have done or suggest something else that works.
I thank you in advance for you help
Emerson
  댓글 수: 2
Andrei Bobrov
Andrei Bobrov 2012년 10월 25일
A=[
1
2
3
4
5
6
7
8
9
10],
B=[
1 4
3 10
6.5 15
8 17
7.4 47
9 59]
out = [A, nan(numel(A),1)]
[a,b] = ismember(A,B(:,1))
out(a,2) = B(b(a),2)
Emerson De Souza
Emerson De Souza 2012년 10월 25일
Thank you Andrei,
these command lines are exactly what I need for general situations.
Emerson

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

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2012년 10월 15일
편집: Azzi Abdelmalek 2012년 10월 15일
C=nan(numel(A),1)
for k=find(ismember(A,B(:,1))==1)
C(k)=B(find(B(:,1)==A(k)),2)
end
  댓글 수: 3
Matt Fig
Matt Fig 2012년 10월 25일
Give an example A and B that actually cover the type of data you will be encountering (this is what you should have done when you asked the first time!). Make sure your two example arrays cover all aspects of the real data...
Emerson De Souza
Emerson De Souza 2012년 10월 25일
Hi Matt Fig,
I absolutely agree with you, I should have thought more in detail before asking. Now reformulating the problem:
1)A and B are arrays with arbitrary number of rows and columns. Their values are elements of Real Numbers (exclude only complex numbers).
2)The array C is constructed as follows:
(i) The first column of C is identical with the first column of A,
(ii) The second column of C is initially filled with NaN,
(iii) Whenever there is a match between one element of the first column of A with one element of the first column of B, then the element of the second column of C equals the value of the element of the second column of B.
Fortunately, Andrei understood between my lines above and fixed the problem. Thank you anyways for your attention
Emerson

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

추가 답변 (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