x=[1 2 3 4]y=[2 4 5 10]x1=[1,1.5,2.2,3.5,4] how to get previous matching value(from y) for x1 by refering x expected answer y1=[2 2 4 5 10] without forloop

1 visualizzazione (ultimi 30 giorni)
for i=1:numel(x1)
Idxfound = find (abs(x-x1(i)) < 0.00001); % abs(x-x1(i)) < 0.1
if isempty(Idxfound)
Idxfound=find(x < x1(i));
if isempty(Idxfound)
if i==1
y1(i) = y(1);
else
y1(i)=y1(i-1);
end
else
Idxfound=Idxfound(end);
y1(i) = y(Idxfound);
end
else
y1(i) = y(Idxfound);
end
end
end

Risposta accettata

Stephen23
Stephen23 il 23 Dic 2021
x = [1,2,3,4];
y = [2,4,5,10];
x1 = [1,1.5,2.2,3.5,4];
%y1=[2,2,4,5,10];
y1 = interp1(x,y,x1,'previous')
y1 = 1×5
2 2 4 5 10
  4 Commenti

Accedi per commentare.

Più risposte (1)

KSSV
KSSV il 23 Dic 2021
x=[1 2 3 4];
y=[2 4 5 10];
x1=[1,1.5,2.2,3.5,4] ;
% y1=[2 2 4 5 5] ;
y1 = interp1(x,y,x1)
y1 = 1×5
2.0000 3.0000 4.2000 7.5000 10.0000
  5 Commenti
KSSV
KSSV il 23 Dic 2021
x=[1 2 3 4];
y=[2 4 5 10];
x1=[1,1.5,2.2,3.5,4] ;
% y1=[2 2 4 5 5] ;
n = length(x1);
idx = zeros(n,1) ;
for i = 1:n
[val,id] = sort(abs(x-x1(i))) ;
idx(i) = id(1) ;
end
y1 = y(idx)
deepika Sridhar
deepika Sridhar il 23 Dic 2021
Modificato: deepika Sridhar il 23 Dic 2021
Hi,
I have lakhs of data in x1
is there any option without forloop
Thanks in advance

Accedi per commentare.

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Prodotti


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by