How to manipulate arrays based on the values of the elements in those arrays?
조회 수: 2 (최근 30일)
이전 댓글 표시
I have two arrays with numbers having large decimal digits. One arrays has less elements than the other one. I want a new array from these two arrays such that the size of the new array is same as the smaller array and the elements are chosen from the bigger array such that the elements of the bigger array having value closer to the value of elements of smaller array are kept in the new array. For example, there are two arrays as below aa with more elements and bb with less elements. I want a new array or modify aa such that aa has as many as elements as bb, but contain only those elements of aa, which have values closer to the elements of bb.
aa = [0.098125 0.198125 0.299375 0.398125 0.498125 0.599375 0.698125 0.798125 0.898125 0.998125 1.098125 1.199375 1.298125 1.398125 1.498125 1.598125 1.698125 1.798125 1.898125 1.998125]
bb = [ 0.308116309211060 0.810255701940190 0.923631508158555 1.020140000913084 1.120779974904424 1.315467747799592 1.807664857150094 1.925768333251547 2.017963041795138]
The new array lets say cc should be something like this:
cc = [0.299375 0.798125 0.898125 0.998125 1.098125 1.298125 1.798125 1.898125 1.998125]
댓글 수: 0
답변 (2개)
Azzi Abdelmalek
2013년 6월 4일
편집: Azzi Abdelmalek
2013년 6월 4일
n=numel(bb)
cc=zeros(1,n)
for k=1:n
[~,idx]=min(abs(aa-bb(k)));
cc(k)=aa(idx);
aa(idx)=[];
end
댓글 수: 1
Jan
2013년 6월 4일
Shrinking a in each iteration leads to the same problems as growing. I think, you can omit aa(idx)=[], but if you want to exclude found values, this is faster: aa(idx)= Inf;
Jan
2013년 6월 4일
편집: Jan
2013년 6월 4일
aa = [0.098125 0.198125 0.299375 0.398125 0.498125 0.599375 0.698125 ...
0.798125 0.898125 0.998125 1.098125 1.199375 1.298125 1.398125 ...
1.498125 1.598125 1.698125 1.798125 1.898125 1.998125]
bb = [ 0.308116309211060 0.810255701940190 0.923631508158555 ...
1.020140000913084 1.120779974904424 1.315467747799592 ...
1.807664857150094 1.925768333251547 2.017963041795138]
index = interp1(aa, 1:length(aa), bb, 'nearest', 'extrap')
cc = aa(index)
Or slightly more efficient, but less intuitive:
cc = interp1(aa, aa, bb, 'nearest', 'extrap')
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!