Calculate differences between all values in vector
Mostrar comentarios más antiguos
I'm trying to produce some code that will calculate the differences between nearly all values in a vector.
Specifically, say I have a vector [2 3 1 4]
Starting at 2 and moving through the vector, I need to calculate the difference between 2 and 3 (i.e. -1), 2 and 1, 2 and 4, then 3 and 1, 3 and 4, and then 1 and 4. I don't need to calculate the difference between, say, 3 and 2, and I'm only interested in the differences in one direction.
The vector I want to use the code on will be substantially bigger, and I'd like the output stored in a new, single column vector. I figured diff might provide a way forward, but can't see how to implement it specifying a 'lag'. Any help would be appreciated.
Respuesta aceptada
Más respuestas (2)
Jos (10584)
el 7 de Abr. de 2014
Editada: Jos (10584)
el 7 de Abr. de 2014
V = [2 3 1 4] ;
D1 = bsxfun(@minus,V(:), V(:).') % square form
% another option, only unique combinations, requires less memory
D2 = arrayfun(@(k) V(k:end)-V(k), 1:numel(k),'un',0)
D2 = [D2{:}]
3 comentarios
Ondrej
el 17 de En. de 2015
There is a small bug I believe. It should be
D2 = arrayfun(@(k) V(k:end)-V(k), 1:numel(V),'un',0)
Soyy Tuffjefe
el 14 de Ag. de 2021
Editada: Soyy Tuffjefe
el 14 de Ag. de 2021
I have a 5x1000 matrix (numerical entries),
M=[1 5 8 75 120;
1 25 18 5 10;
⋮ ⋮ ⋮ ⋮ ⋮
7 39 118 125 10]
and want to apply her or his code:
D2 = arrayfun(@(k) V(k:end)-V(k), 1:numel(k),'un',0)
D2 = [D2{:}
to every row of M, please, could anybody modify this code for this job.
Thanks in avanced!
Mehri Mehrnia
el 19 de Mayo de 2022
A great idea.
any body knows computation cost of bsxfun(@minus,V(:), V(:).')???
I mean linear or 2nd order or...
I work with arrays in order of millions, that's why it's important for me.
Mischa Kim
el 7 de Abr. de 2014
Swisslog, you could use
pdist([2 3 1 4]',@(x,y) x-y)
1 comentario
Swisslog
el 7 de Abr. de 2014
Categorías
Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!