Calculate differences between all values in vector

42 次查看(过去 30 天)
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.

采纳的回答

David Sanchez
David Sanchez 2014-4-7
my_vct = [2 3 1 4 5 6];
L = numel(my_vct);
tmp_vct = [my_vct(2:end) my_vct(end)];
x = my_vct - tmp_vct;
sol = zeros(L-1,L);
for k=2:L
tmp_vct = [my_vct(k:end) my_vct((L-k+2):end)];
sol(k-1,:) = my_vct - tmp_vct;
end
sol =
-1 2 -3 -1 -1 0
1 -1 -4 -2 0 0
-2 -2 -5 0 0 0
-3 -3 0 0 0 0
-4 0 0 0 0 0
  3 个评论
Swisslog
Swisslog 2014-4-7
...and
sol=sol(:);
sol(sol==0) = [];
to reduce to a single column I guess. Many thanks!

请先登录,再进行评论。

更多回答(2 个)

Jos (10584)
Jos (10584) 2014-4-7
编辑:Jos (10584) 2014-4-7
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 个评论
Soyy Tuffjefe
Soyy Tuffjefe 2021-8-14
编辑:Soyy Tuffjefe 2021-8-14
Thanks to Jos (10584) for your code...
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
Mehri Mehrnia 2022-5-19
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
Mischa Kim 2014-4-7
Swisslog, you could use
pdist([2 3 1 4]',@(x,y) x-y)

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by