How can I sum values at specific point
6 views (last 30 days)
Show older comments
First , I have a thousand height values depending on position values. I want to order these values according to a rule. Because some height values are at the exact positon or same position. I need to sum these height values and express it with position values or plot it. For ınstance
P=[1 2 4 1 3 2 2 5]
H=[3 1 1 2 3 1 4 2]
I want these vectors
P_ordered=[1 2 3 4 5]
H_sum =[5 6 3 1 2]
Second,now, I have some other height values depends on position values named H_original and I want to do
H_original-H_sum = H_final
and plot(P,H_final,)
P=[-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10]
H_original=[10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 ]
What I want to reach
P=[-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10]
H_final=[10 10 10 10 10 10 10 10 10 10 5 4 7 9 8 10 10 10 10 10 10 ]
Plot(P,H_final)
1 Comment
Answers (2)
the cyclist
on 2 Jul 2014
First part:
If P is always some ordering of the numbers 1-N, then this simple code will work:
P_ordered = unique(P);
H_sum = accumarray(P',H')';
If not, can you please supply a more general example of how P might look?
Roger Stafford
on 2 Jul 2014
I have called the larger P array, 'P_large', to distinguish it from the original P. The following code assumes that each element of P_ordered will match one and only one element of P_large. It also assumes that P and H are the same size, and that P_large and H_original are the same size.
P = [1 2 4 1 3 2 2 5];
H = [3 1 1 2 3 1 4 2];
P_large =[-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10];
H_original=[10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10];
[P_ordered,~,iP] = unique(P);
H_sum = accumarray(iP,H,size(P_ordered));
[~,iH] = ismember(P_ordered,P_large);
H_final = H_original-accumarray(iH,H_sum,size(P_large));
Note: In your example in obtaining H_final you appear to have misaligned H_sum with H_original by one position. This code assumes this was an error.
See Also
Categories
Find more on Surface and Mesh Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!