How to manipulate arrays based on the values of the elements in those arrays?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (2)
Azzi Abdelmalek
el 4 de Jun. de 2013
Editada: Azzi Abdelmalek
el 4 de Jun. de 2013
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 comentario
Jan
el 4 de Jun. de 2013
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
el 4 de Jun. de 2013
Editada: Jan
el 4 de Jun. de 2013
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 comentarios
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!