Operation with components of a vector and for loop

1 回表示 (過去 30 日間)
Vittorio Locatelli
Vittorio Locatelli 2022 年 5 月 3 日
コメント済み: Monica Roberts 2022 年 5 月 3 日
Good morning everyone,
given a vector of n components, I would need to perform the following operation: dist = n- (n-1) for all n.
Since the size of the vector is an unknown I interrogated the software to derive this and then I thought of building a for loop as described below. I think I understand the problem, I think that in the first matlab cycle I can't identify the second component to subtract and does not identify the component "n-1 = 0" but I can't think of anything alternative.
[nlocsrif,ncol]=size(locsrif)
for i = 1:nlocsrif
picco = sprintf("locsrif(%d)", i)
distpic= picco(i)-picco(i-1)
end
I trust in your solution and thank you in advance for the answers
Greetings
  2 件のコメント
David Hill
David Hill 2022 年 5 月 3 日
distpic=diff(picco);
Vittorio Locatelli
Vittorio Locatelli 2022 年 5 月 3 日
Thanks a lot to you too.

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

採用された回答

Monica Roberts
Monica Roberts 2022 年 5 月 3 日
You might consider checking out the built-in matlab function "diff". Or you could loop from 2 to nlocsrif instead.
  2 件のコメント
Vittorio Locatelli
Vittorio Locatelli 2022 年 5 月 3 日
Thanks for the quick reply. Y = diff (X) seems to work for me. It is not possible for me to start from element 2 since by doing so I would not be able to calculate component2-component1.
Monica Roberts
Monica Roberts 2022 年 5 月 3 日
You might notice that Y is a different size to X. This is because it subtracts the elements of X starting at X(2) - X(1). Let's say your data looks like:
X = [2,3,7,8,3,1];
Then Y = 1, 4, 1, -5, -2. X is of size 6, Y is of size 5. To get this we started by subtracting X(2) - X(1) or 3 - 2.
Should the first value of Y be X(1) - 0 instead? If so, you could do this:
X0 = [0,X];
Y = diff(X0);

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by