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)]"

 Réponse acceptée

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

4 commentaires

Thank you!
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?
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);
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?

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by