How do I subtract elements in array? (1 x 40)

For example:
A = [8 3 10 7 15 12 16 14 20 18 12 8]
so that I can create two variables that are the difference between each pair in the vector..
result1 = [5 3 2] --> "[(8-3) (15-12) (20-18]"
result2 = [3 2 4] --> "[(10-7) (16-14) (12-8)]"

 採用された回答

Walter Roberson
Walter Roberson 2018 年 3 月 7 日

0 投票

all_results = -diff(reshape(A,2,[]));
result1 = all_results(1:2:end);
result2 = all_results(2:2:end);

4 件のコメント

Lawrence Besong
Lawrence Besong 2018 年 3 月 7 日
Thank you!
Lawrence Besong
Lawrence Besong 2018 年 3 月 7 日
Is it possible to make loop or something if I have 18 sets of (1 x 40) arrays to give me the mean of each result1 & result 2 for all 18 arrays?
Walter Roberson
Walter Roberson 2018 年 3 月 7 日
Put all of the data together into A as an 18 x 40 array. Do not put it into separate variables: that way lies madness.
Once it is in an 18 x 40 array, then
all_results = squeeze( -diff( reshape(A, size(A,1), 2, []), 2 ) );
result1 = all_results(:, 1:2:end);
result2 = all_results(:, 2:2:end);
mean_result1 = mean(result1);
mean_result2 = mean(result2);
Lawrence Besong
Lawrence Besong 2018 年 3 月 8 日
Thank you so much. There seems to be something wrong with this code for the (18 x 40)... I am getting weird and not the corrects results for result1 and result2. The code for the (1x40) array is working perfectly though. Any suggestions?

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by