Creating new vectors containing values based on for loop outcome.
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Michael Abram
el 31 de Dic. de 2020
I would like to create a new vector which contains values from b which correspond to the closest values from a. I mainly code in python and am new to Matlab. The only thing i can think of at the moment is an if statement which i know would most likely be inefficient. Essentially i would need to create new vectors for each value in a. The following is my code. Any help is greatly appreciated, thanks in advance.
a=[1250 2320 3520 7650];
b= [3700 6766 8888 1212 2000 5555 9998 3000];
vals=zeros(7,1);
n=1;
for i = b
differences = abs(a-i);
[minDiff, indexOfMinDiff] = min(differences);
closestValue = a(indexOfMinDiff);
vals(n)= closestValue;
n=n+1;
end
edges = unique(vals)
counts = histc(vals(:), edges)
0 comentarios
Respuesta aceptada
dpb
el 31 de Dic. de 2020
Editada: dpb
el 31 de Dic. de 2020
vals=interp1(a,a,b,'nearest','extrap');
For above a,b:
>> vals
vals =
3520.00 7650.00 7650.00 1250.00 7650.00 7650.00 3520.00
>>
10 comentarios
dpb
el 2 de En. de 2021
Editada: dpb
el 2 de En. de 2021
filename = 'Centroids.txt';
[inCent,delimiterOut]=importdata(filename);
filename = 'EPdata.txt';
[X,delimiterOut]=importdata(filename);
vals=interp1(inCent,inCent,X,'nearest',"extrap");
n=0;
cent=zeros(numel(inCent),1);
for i = inCent.'
n=n+1;
cent(n)=mean(X(vals==i));
end
removing duplicated variables; only transposing where needed and eliminate unnecessary temporaries and the explicit find for the logical addressing vector.
Alernatively, can eliminate the explicit loop with
filename = 'Centroids.txt';
[inCent,delimiterOut]=importdata(filename);
filename = 'EPdata.txt';
[X,delimiterOut]=importdata(filename);
vals=interp1(inCent,inCent,X,'nearest',"extrap");
cent=arrayfun(@(i) mean(X(X==vals)),vals);
NB: air code, untested....
Más respuestas (0)
Ver también
Categorías
Más información sobre Debugging and Analysis en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!