how to make a function that calculate consective difference of elements of a vector

4 ビュー (過去 30 日間)
Hi every one. I am going to attempt that query.. Write a function called neighbor that takes as input a row vector called v and creates another row vector as output that contains the absolute values of the differences between neighboring elements of v. For example, if v == [1 2 4 7], then the output of the function would be [1 2 3]. Notice that the length of the output vector is one less than that of the input. Check that the input v is indeed a vector and has at least two elements and return an empty array otherwise. You are not allowed to use the diff built‐in function. I am trying that code, getting an error in for loop because its inner statement (vi+1) creating problem.To me instead of for loop while loop will be implement. But how i not know.Any correction will be highly appreciable..
function [A]=neighbor(v)
if isvector(v) && length(v)>=2 % checking whether v is a vector and have two elements
for i=1:length(v)
A=v(i+1)-v(i); % getting the absolute values of v(i+1)-v(i)
end
else
A=[];
end
end
  1 件のコメント
Andrei Bobrov
Andrei Bobrov 2015 年 5 月 27 日
編集済み: Andrei Bobrov 2015 年 5 月 27 日
without diff function
conv2(v(:)',[1, -1],'valid')

サインインしてコメントする。

採用された回答

Thorsten
Thorsten 2015 年 5 月 27 日
編集済み: Thorsten 2015 年 5 月 27 日
Why not using your original solution with the changes that Yoav suggested, plus an additional abs() to get the absolute difference?
function [A]=neighbor(v)
if isvector(v) && length(v)>=2 % checking whether v is a vector and have two elements
for i=1:length(v) - 1 % *** -1 otherwise i+1 becomes invalid
A(i)=abs(v(i+1)-v(i)); % getting the absolute values of v(i+1)-v(i)
end
else
A=[];
end
end
Instead of the for loop, you can use
A = abs(v(2:end) - v(1:end-1));
If you run into problems, please report input and the error it produces.
  1 件のコメント
Muhammad Usman Saleem
Muhammad Usman Saleem 2015 年 5 月 27 日
@ Thorsten thanks.. Actually he write it very briefly.. that why i was not using this.. Your other code has already share by @Stephen Cobeldick .. please see his answer..

サインインしてコメントする。

その他の回答 (1 件)

Yoav Livneh
Yoav Livneh 2015 年 5 月 27 日
If you insisnt on using for loops you just need to change the limit of the for loop to
length(v)-1
and of course add
A(i) = ...
so you get a vector and not just a single value.
But you can just use indexing instead of loops to solve this:
A = v(2:end) - v(1:end-1);

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by