How to manipulate arrays based on the values of the elements in those arrays?
1 次查看(过去 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!